这是父组件的代码 . 它有一个按钮,也包含一个子组件 .
我的问题是:当 state
的值发生变化时,React能否发送 prop
?如果没有,那么当状态发生变化时,我需要做什么才能发送道具?
- 虽然组件将在状态更改后重新渲染,但我不得不单击该按钮两次以查看文本中的更改 .
How do I make it happen in sync with the change of state in the parent component?
父组件代码:
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>
);
}
}
2 回答
当我们点击Click me按钮
handleButtonClick()
被调用时,里面调用setState()
在此调用中,页面将重新呈现 . 这导致传递给子组件的props的值发生变化 . 所以当您使用
setState
更改父级的状态时,传递给子组件的道具也会发生变化 .更新到您更新的问题:
删除if条件,因为它是导致问题的一个,并且道具正确更新
您不应该使用componentWillRecieveProps,因为它是遗留的并导致问题 . 检查文档:componentWillRecieveProps