gpt4 book ai didi

javascript - 如何将回调函数传递给父级

转载 作者:行者123 更新时间:2023-11-30 13:53:13 26 4
gpt4 key购买 nike

假设我们有一个Container组件如下。

class Container extends React.Component {
handleClose = () => {
// need to ask 'Content' is it okay with closing
const isContentAgree = /* */;
if (isContentAgree) this.props.onClose();
};

render () {
const {content: Content} = this.props;
return (
<button onClick={this.handleClick}>Close</button>
<Content {/* some container-specific props */} />
);
}
}

用法:

<Container content={SomeComponent}/>

在这种情况下,如何将回调函数从 SomeComponent 传递到 Container?当单击 Container 中的按钮并返回 bool 值时将调用此回调。

最佳答案

您需要将 isContentAgree 保持在 state 并且您可以传递函数来将 isContentAgree 切换到子组件。

class Container extends React.Component {
constructor(props) {
super(props);
this.state = {
isContentAgree: false
}
}

toggleContentAgree = (e) => {
this.setState({ isContentAgree: e.target.value })
}

handleClose = () => {
// need to ask 'Content' is it okay with closing
const isContentAgree = this.state.isContentAgree;
if (isContentAgree) this.props.onClose();
};

render () {
const {content: Content} = this.props;
return (
<button onClick={this.handleClose}>Close</button>
<Content toggleContentAgree={this.toggleContentAgree} />
);
}
}

关于javascript - 如何将回调函数传递给父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57800910/

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