reactjs - How to Set state of a component from within another component in react
问题描述
I have a child react component and I would like to set the state of the parent component from the child component. How do i achieve it ?
class Parent extends React.Component{
constructor( props ){
super(props);
this.state ={
request:{
ip: "",
location:""
}
};
}
render(){
return(
<Child request={this.state.request} />
);
}
}
Now in the child page I want to set the value of ip.
class Child extends React.Component{
constructor( props ){
super(props);
this.onChange = this.onChange.bind( this );
}
render(){
return(
<Input id = "ip" type = "text" name = "case" onChange = { ( e ) => { this.onChange( e ); } }/>
);
}
onChange( e ) {
this.setState( { ...this.props.request, ip: e } );
}
}
解决方案
我不确定这是否是最正确的(也是最反应的方式),但我会定义一个函数来更改父类中父类的状态并将其作为道具传递给孩子,如下所示:
class Parent extends React.Component{
constructor( props ){
super(props);
this.state ={
request:{
ip: ""
}
};
}
changeIP = (newIp) => {
// Do your checks beforehand
this.setState({
request: {
...this.state.request,
ip: newIp
}
})
}
render(){
return(
<Child request={this.state.request} changeIP={this.changeIP} />
);
}
}
然后在您的子类中,当您想要设置父类的状态时,您可以像这样调用该函数:
class Child extends React.Component{
constructor( props ){
super(props);
this.onChange = this.onChange.bind( this );
}
render(){
return(
<Input id = "ip" type = "text" name = "case" onChange = { ( e ) => { this.onChange( e ); } }/>
);
}
onChange( e ) {
this.props.changeIP(e.target.value) // I think it should be 'e.target.value', make sure you pass the right value here
}
}
希望这可以帮助
推荐阅读
- java - 当在所需对象上获得锁定时,同步块无法按预期工作,但在应用于“this”时工作正常
- protocol-buffers - 传递动态对象
- tensorflow - keras clear session() 、 del models 和 gc.collect() 是如何工作的?
- r - 如何通过R中x的数学差异找到哪些行相关
- javascript - Typescript 如何使用类转换器初始化混合类型数组
- node.js - 如何在特定时间和日期发送通知(firebase 云消息传递)
- vba - 查找检查后打开链接
- c# - 如何在 C# 中编写通用方式方法
- python - 为什么更好的算法代码的运行时间比原始的算法代码多?
- c# - EPP 返回问候语然后冻结