这是父组件的代码。它有一个按钮,也包含一个子组件。
我的问题是:React 是否能够发送更改prop
的值state
?如果没有,那么当状态发生变化时我需要做什么来发送道具?
如何使其与父组件中的状态更改同步发生?
父组件的代码:
class ParentComponent extends Component {
constructor(props) {
super(props);
this.state = {
toBeDrafted: false
};
this.handleButtonClick = this.handleButtonClick.bind(this);
}
handleButtonClick() {
this.setState({
toBeDrafted: true
});
}
render() {
return (
<React.Fragment>
<button onClick={this.handleButtonClick}>Click Me</button>
<ChildComponent valueOfButton={this.state.toBeDrafted} />
</React.Fragment>
);
}
}
这是子组件的代码
class ChildComponent extends Component {
constructor(props) {
super(props);
this.state = {
toBeUpdated: false
};
}
componentWillReceiveProps() {
if (this.props.valueOfButton === true) {
this.setState({
toBeUpdated: !this.state.toBeUpdated
});
}
}
render() {
return (
<React.Fragment>
<p>
The Button has been
{
this.state.toBeUpdated === true
? "clicked"
: "not clicked"
}
</p>
</React.Fragment>
);
}
}
当我们点击 Click me 按钮时handleButtonClick()
,它会在里面调用setState()
在这次调用中,页面被重新呈现。这导致传递给子组件的 props 值发生变化。因此,当您使用setState
传递给子组件的 props更改父组件的状态时,也会更改。
更新您更新的问题:
componentWillReceiveProps() {
this.setState({
toBeUpdated: !this.state.toBeUpdated
});
}
删除 if 条件,因为它是导致问题的原因,并且道具已正确更新
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句