javascript – 在React中从父组件到子组件共享状态
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 在React中从父组件到子组件共享状态,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2330字,纯文字阅读大概需要4分钟。
内容图文
我遇到了将父组件的状态绑定到子状态的问题.看一下代码:
父组件:
class ParentForm extends React.Component {
constructor(){
super();
this.state = {
showDialog: false
};
}
toggleDialog() {
this.setState({showDialog: !this.state.showDialog});
}
return (
<div >
<Button color='primary' onClick={() => this.toggleDialog()}></Button>
<MyDialog open={this.state.showDialog}/>
</div>
);
}
子组件:
export default class MyDialog extends Component {
constructor(props){
super(props);
this.state = {
open: this.props.open
};
}
handleRequestClose = () => {
this.setState({ open: false });
};
render() {
return (
<div>
<Dialog
fullScreen
open={this.state.open}
onRequestClose={() => this.handleRequestClose()}
transition={<Slide direction="up" />}
>
<DialogTitle>{'Title'}</DialogTitle>
<DialogContent>
<DialogContentText>
This is my dialog
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={() => this.handleRequestClose()} color="primary">Close</Button>
</DialogActions>
</Dialog>
</div>
);
}
}
在Parent Component中,如果我将state.showDialog属性设为true,则在页面加载时将打开该对话框.但是一旦我关闭它一次,我再也无法打开它了.如果我将其设置为false,则在页面加载时不会加载,即使单击父组件上的按钮,也无法打开对话框.提前感谢您抽出宝贵时间提供帮助.
解决方法:
由于您是基于父级设置本地状态,因此您需要在v16.3.0之前使用componentWillReceiveProps或之后使用getDerivedStateFromProps / memoization / key修改,因为您的状态仅在第一次设置,之后从未设置.但是,您甚至不需要MyDialog组件中的本地状态,您可以只使用Props并从子组件传递到父组件.
亲
class ParentForm extends React.Component {
constructor(){
super();
this.state = {
showDialog: false
};
}
toggleDialog() {
this.setState({showDialog: !this.state.showDialog});
}
closeDialog() {
this.setState({showDialog: false})
}
return (
<div >
<Button color='primary' onClick={ this.toggleDialog}></Button>
<MyDialog open={this.state.showDialog} closeDialog={this.closeDialog}/>
</div>
);
}
MyDialog(小孩)
export default class MyDialog extends Component {
constructor(props){
super(props);
}
render() {
return (
<div>
<Dialog fullScreen open={this.props.open} onRequestClose={this.props.closeDialog} transition={<Slide direction="up" />}>
<DialogTitle>{'Title'}</DialogTitle>
<DialogContent>
<DialogContentText>
This is my dialog
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={this.props.closeDialog} color="primary">Close</Button>
</DialogActions>
</Dialog>
</div>
);
}
}
内容总结
以上是互联网集市为您收集整理的javascript – 在React中从父组件到子组件共享状态全部内容,希望文章能够帮你解决javascript – 在React中从父组件到子组件共享状态所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。