[英]Unable to open/close modal with parent class component and child functional component
I have a parent component in which I'm struggling to properly open/close the child component (modal).我有一个父组件,我正在努力正确打开/关闭子组件(模态)。 The two code boxes below are simplified examples of my components.下面的两个代码框是我的组件的简化示例。
EDIT: Here is a code sandbox with the following code -- there isn't an actual modal, however i've logged all of the stateful values that I assume will have an effect on this problem and you can see how they change/don't change as I hope they would.编辑:这是一个带有以下代码的代码沙箱——没有实际的模式,但是我已经记录了我认为会对这个问题产生影响的所有有状态值,你可以看到它们是如何改变/改变的不要像我希望的那样改变。
Thanks to whoever reaches out, and if you have any clarifying questions feel free to ask!感谢任何伸出援手的人,如果您有任何澄清问题,请随时提出!
class Parent extends Component {
constructor(props) {
super(props);
this.showModal = this.showModal.bind(this);
this.closeModal = this.closeModal.bind(this)
this.state = {
showModal: false
};
this.showModal = this.showModal.bind(this)
this.closeModal = this.closeModal.bind(this)
}
showModal() {
this.setState({ showModal: true });
}
closeModal() {
this.setState({ showModal: false });
}
render() {
return (
<MenuItem onClick={this.showModal}>
<ChildComponent
prop1={prop1}
isOpen={this.state.showModal}
closeModal={this.closeModal}
/>
</MenuItem>
)}
const ChildComponent = ({
prop1,
isOpen,
closeModal
}) => {
const [modalOpen, setModalOpen] = useState(isOpen)
useEffect(() => {
setModalOpen(isOpen)
},[isOpen])
console.log('isopen on child', isOpen)
console.log('modalOpen', modalOpen)
return (
<div>
{modalOpen && (
<button
onClick={() => {
setModalOpen(false)
closeModal()
}}
>
{'click to close modal'}
</button>
)}
</div>
)}
)}
I figured out my problem!我发现了我的问题!
In my parent component the onClick handler that sets the modal open wrapped my child component.在我的父组件中,设置模态打开的 onClick 处理程序包装了我的子组件。 I needed to remove it and conditionally render it separately like so:我需要删除它并有条件地单独渲染它,如下所示:
<div>
<div onClick={this.showModal}>{"Click here to open modal"}</div>
{this.state.showModal && (
<ChildComponent
prop1={prop1}
isOpen={this.state.showModal}
closeModal={this.closeModal}
/>
)}
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.