[英]Passing value from Parent to Child in Reactjs using props
每当我单击send questions
按钮时,我都试图将theExpert.email
值传递给另一个子组件。
这是Parent类的构造函数
constructor() {
super();
this.state = {
textbox: '',
category: '',
exp: '',
hide: false
};
this.hideButton = this.hideButton.bind(this);
}
后续的函数隐藏一旦点击该按钮并保存的值theExpert.email
在exp
( value
由于传递正确console.log
打印出来)
hideButton (value) {
this.setState({ hide: true });
this.setState({
exp: value
});
console.log(value)
}
这是按钮,一旦我单击它,它将值传递给hideButton
<div>
{!this.state.hide ? (
<button onClick={() => this.hideButton(theExpert.email)}>Ask Me!</button>
) : null}
</div>
现在,我要做的就是单击“ Send Questions
按钮后,我将重定向到子组件Questions.js
,并将theExpert.email
的值theExpert.email
给该组件。按钮“ Send Questions
:
<div>
<p>
{(this.state.hide) && (
<Link to="/questions">
<button
style={{ background: "green", color: "white" }}
>
Send Question
</button>
</Link>
)}
</p>
</div>
我如何在子类中检索value
以使用它创建发布请求
我认为我们由于懒惰而引起的问题。 基本上,您只是将hide设置为true并重新渲染组件及其所有子组件,但从未设置exp的期望值。
所以代替
hideButton (value) {
this.setState({ hide: true });
this.setState({
exp: value
});
console.log(value)
}
尝试
hideButton (value) {
this.setState(prevState=>{
prevState= {
...prevState
hide: true ,
exp: value
}
return prevState
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.