首页 > 解决方案 > 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 } );
  }

}

标签: reactjs

解决方案


我不确定这是否是最正确的(也是最反应的方式),但我会定义一个函数来更改父类中父类的状态并将其作为道具传递给孩子,如下所示:

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
    }

  }

希望这可以帮助


推荐阅读