2015-12-13 130 views
0

我目前正在学习ReactJS,我正在尝试创建一个简单的Lightbox。我有三个名为ThumbnailContainer,Thumbnail和Lightbox的组件。如下图所示:ReactJS从子状态设置父状态onClick处理程序

var ThumbnailContainer = React.createClass({ 
    render: function(){ 
    var thumbnails = this.props.thumbnail_data 
    var thumbnail_list = thumbnails.map(function(thumbnail){ 
    console.log(thumbnail); 
     return <Thumbnail key={thumbnail.id} post={thumbnail}/> 
    }); 

    return (
     <div id="thumbnail-container"> 
    {thumbnail_list} 
     </div> 
    ); 
    } 
}); 

var Thumbnail = React.createClass({ 
    getInitialState: function(){ 
    return { 
     display: false 
    }; 
    }, 
    openLightbox: function(e){ 
    e.preventDefault(); 
    this.setState({display: true}); 
    }, 
    closeLightbox: function(e){ 
    this.setState({display: false}); 
    }, 
    render: function(){ 
    var post = this.props.post; 
    return (
     <div className="post" onClick={this.openLightbox}> 
      <img className="post-image" src={post.image} /> 
      { this.state.display ? <Lightbox image={post.image} closeHandler={this.closeLightbox}/> : null} 
     </div> 
    ); 
    } 
}); 

var Lightbox = React.createClass({ 
    render: function(){ 
    var image = this.props.image 
    return (
     <div> 
      <div className="lightbox-background" onClick={this.props.closeHandler}></div> 
      <div className="lightbox-content" onClick={this.props.closeHandler}> <img src={image} /></div> 
     </div> 
    ) 
    } 
}); 

打开灯箱工作正常,但我有在关闭灯箱设置状态的问题。出于某种原因,this.setState实际上并没有将状态设置为false,它在调用setState之后仍然设置为true。

我在这里错过了什么吗?我有一些例子here

回答

1

的问题是,你的openLightbox()方法获取closeLightbox()调用后立即召开了一个小提琴,所以状态变化两次:display被设置为false然后回到true。这是因为您有两个onClick处理程序,它们重叠。

最简单的修复方法是将e.stopPropagation()放入您的closeLightbox()方法中。

+0

感谢您的回答!我觉得我应该知道这一点,以及事件冒泡如何起作用。你有什么建议如何改善整体? –

+1

如果你能够使用Babel进行传输,你可能需要考虑使用ES6,这样你可以使用'const'来使你的意图更清晰。您可能还想看看新的无状态功能组件,因为(例如)您的'Lightbox'类将适合于。 – TwoStraws

+0

感谢您的提示! @TwoStraws肯定会研究这些。 –