繁体   English   中英

如何在反应中将状态从子组件传递到父组件

[英]how to pass state from child component to parent component in reacts

我有一个父组件

class ParentComponent extends React.PureComponent {       
       render(){
        return(   
        //IN HERE I'm calling child parent    
          <ChildComponent/>
        )
        }        
        }

class ChildComponent extends React.PureComponent {  
    constructor(props) {
        super(props);
        this.state = {
          sample: '',        
        };  
    }

如何将示例状态获取到父组件?

  1. 因此,在父组件处创建一个接收值作为回报的方法。

     StateValue = (value) =>{ console.log(value); }
  2. 将此方法作为道具传递给子组件。

     <ChildComponent method={this.StateValue}/>
  3. 在子组件处将状态值传递给步骤 2 中接收到的方法 props。

     constructor(props) { super(props); this.state = { sample: 'hi', }; } render(){ this.props.method(this.state.sample) return( <></> )

您将从父组件中的道具获取 StateValue 方法中的状态值。

尝试这个:

class ParentComponent extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {
          sample: '',        
        };  
    }

      render(){
        return(   
          <ChildComponent sample={this.state.sample} setState={(sample) => this.setState({ sample })} />
          )
         }        
        }

class ChildComponent extends React.PureComponent {    
// you can now call this.props.setState(value); to set parent component state.
// and access the sample state: this.props.sample;
    }

一种选择是将回调指定为道具。 像这样:

class ParentComponent extends React.PureComponent {
      onSample = (sample) => {
          // handle sample
       }

       render(){
        return(   
        //IN HERE I'm calling child parent    
          <ChildComponent
            callback={this.onSample}
          />
        )
        }        
      }

class ChildComponent extends React.PureComponent {  
    constructor(props) {
        super(props);
        this.state = {
          sample: '',        
        };
        this.onSample = props.callback
        // call later on via this.onSample(<sample>);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM