作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
假设我们有一个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/
我是一名优秀的程序员,十分优秀!