此问题已在此处有答案:
How can I update the parent's state in React?(24回答)
2小时前关闭
我尝试使用React的componentWillUnmount
功能,并通过click事件从子组件更改prop的值。我想我愿意使用“提升状态”,并希望使用React的componentWillUnmount
属性。
export default class App extends React.Component {
constructor(props){
super(props);
this.state={
show:true
}
}
render() {
const toggleDisplay=()=>{
this.setState({show:!this.state.show});
}
return (
<div className="App">
{this.show&&<ChildrenUnmounting onclickfun={toggleDisplay} />}
</div>
);
}
}
class ChildrenUnmounting extends React.Component {
constructor(props) {
super(props);
alert("constructor is called!");
this.state={
onclickfun:props.onclickfun,
}
alert("constructor is called!");
}
render() {
return (
<>
{alert("render is called!")}
<h1>This content is shown!</h1>
<button onClick={this.state.onclickfun}>
Toggle View
</button>
</>
);
}
componentWillUnmount() {
alert("componentWillUnmount is called!");
}
}
3条答案
按热度按时间zzoitvuj1#
在Appcomponent的render()方法中,使用的是this.show而不是this.state.show。更新行
到
通过此更改,show state属性将在render()方法中正确引用,并且将根据其值显示或隐藏子组件。
4nkexdtk2#
在
App
组件的返回函数中,条件具有不正确的变量(this.show
代替了this.state.show
)。正因为如此,你正面临着这样的问题。当前代码:
像这样更新:
mnowg1ta3#
您没有正确地将状态设置器向下传递给子组件。相反,您将其设置为状态值/变量。
代码应该是这样的: