【发布时间】:2017-09-14 20:41:35
【问题描述】:
我的第一个 react 项目的第一个问题。
我正在尝试弄清楚如何在特定的 onClick 链接上最好地影响组件,以便能够重新触发此效果并且不使其受到页面上其他链接的影响。前两个问题有效,但我似乎无法让其他链接不影响组件。
我的页面上有一个 DisplayLightbox 组件,它接受几个值
<div>
<DisplayLightbox
showLightbox = {this.state.showLightbox}
lightboxValue = {this.state.travelCity}
/>
</div>
我要触发灯箱的链接正在调用一个设置状态(并发送道具)的函数。这部分似乎工作正常。
onClick={() => this.showLightbox(el.field_city)}
showLightbox(travelCity){
this.setState({
showLightbox: true,
travelCity: travelCity,
});
}
在我的 DisplayLightbox 组件中,componentWillReceiveProps 确实将 state 设置为 true,这会在 div 中添加 lb-active 类,该类从 css 中显示灯箱 div。这似乎很好。
class DisplayLightbox extends React.Component {
constructor(props) {
super(props);
this.state = {
showLightbox: false,
};
}
componentWillReceiveProps(nextProps) {
if (nextProps.showLightbox !== this.state.showLightbox) {
this.setState({ showLightbox: nextProps.showLightbox });
}
}
closeLightbox() {
this.setState({
showLightbox: false,
});
}
render() {
var lbActive = (this.state.showLightbox === true) ? "lb-active" : ""
return <div className={"lightbox " + lbActive }>
<div className={"lightbox-close " + lbActive } onClick={() =>
this.closeLightbox()}>CLOSE</div>
Copy in lightbox
</div>;
}
}
查看它,我发现由于 props 不受组件控制并且是只读的,因此一旦将其设置为 True 并且我通过将 showLighbox 的状态设置回 false 来关闭 div,nextProps.showLightbox 仍然为 true。因此,如果我关闭它(closeLightbox)并单击页面上的另一个 onClick,它仍会查看我的组件,看到 nextProps.showLightbox 仍设置为 TRUE 并打开灯箱。
如果该特定链接是被点击的链接,我只希望打开灯箱。让所有其他链接都将 showLightbox 的状态设置为 false 似乎有点矫枉过正,所以我猜我没有正确看待这个问题。
谢谢
【问题讨论】:
标签: reactjs