gpt4 book ai didi

ReactJS 重置 componentWillReceiveProps 的 props

转载 作者:行者123 更新时间:2023-12-03 14:32:17 25 4
gpt4 key购买 nike

我的第一个 React 项目的第一个问题。

我试图弄清楚如何在特定的 onClick 链接上最好地影响组件,以便能够重新触发此效果并且不让它受到页面上其他链接的影响。前两个请求有效,但我似乎无法让其他链接不影响该组件。

我的页面上有一个 DisplayLightbox 组件,接受几个值

<div>
<DisplayLightbox
showLightbox = {this.state.showLightbox}
lightboxValue = {this.state.travelCity}
/>
</div>

我想要触发灯箱的链接正在调用一个设置状态(并发送 Prop )的函数。这部分似乎工作得很好。

onClick={() => this.showLightbox(el.field_city)}

showLightbox(travelCity){
this.setState({
showLightbox: true,
travelCity: travelCity,
});
}

在我的 DisplayLightbox 组件中,componentWillReceiveProps 确实将 state 设置为 true,这会在 div 中添加 lb-active 类,该类会从 css 中显示 lightbox 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 似乎有些过分了,所以我猜我没有正确地看待这个问题。

谢谢

最佳答案

您可以将 closeLightbox 方法移动到上层组件并从父组件管理 showLightbox 属性。然后组件 DisplayLightbox 将有 3 个 props:showLightboxtravelCity 和方法 closeLightbox

当您将关闭灯箱移动到父组件时,应该不再需要 componentWillReceiveProps 事件。

关于ReactJS 重置 componentWillReceiveProps 的 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46227904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com