如何将状态从子组件传递到父组件

时间:2020-10-08 03:36:15

标签: javascript reactjs

我有一个父级组件

{{1}}

如何获取样本状态到父组件?

3 个答案:

答案 0 :(得分:1)

  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(
         <></>
       )
    

您将通过父组件中的props在StateValue方法中获取状态值。

答案 1 :(得分:0)

尝试一下:

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;
    }

答案 2 :(得分:0)

一个选项是将回调指定为prop。像这样:

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>);
    }