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

时间:2017-03-07 07:30:46

标签: javascript reactjs

我有2个jsx文件,

如何从 Child.jsx Parent.jsx 获取 this.props.result

档案Child.jsx:

class Child extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            result: 'logout'
        };
        this.login_action = this.login_action.bind(this);
        this.logout_action = this.logout_action.bind(this);
    }

    login_action(){
        this.setState({result: 'login'})
    }

    logout_action(){
        this.setState({result: 'logout'})
    }

    render(){
        return(
            <div>
                <h1>{this.state.status}</h1>
                <button onClick={this.login}>Login</button>
                <button onClick={this.logout}>Logout</button>
            </div>
        )
    }
}

导出默认子项;

文件Parent.jsx:

 class Parent extends React.Component {
     render () {
        if(this.props.result.localeCompare("login") > -1){
            return(<Child  status="logout" />)
        }else{
            return(<Child  status="logout"/>)
        }
     }
 }
 render(<Parent/>, document.getElementById('app'));

2 个答案:

答案 0 :(得分:2)

正如文件所说,

  

在React中,共享状态是通过将其移动到需要它的组件的最近共同祖先来完成的。这称为“提升状态”。 (https://facebook.github.io/react/docs/lifting-state-up.html

您应该将“结果”状态移动到父组件。有关从代码中提升状态的示例,请参阅此Plunker

答案 1 :(得分:1)

您需要将回调函数从Parent传递给Child。像这样:

Parent.jsx

class Parent extends React.Component {

  render () {

    if(this.props.result.localeCompare("login") > -1){
        return(<Child onResultChange={(res) => this.onResultChange(res)} status="logout" />)

    }else{
        return(<Child onResultChange={(res) => this.onResultChange(res)} status="logout"/>)

    }
  }

  onResultChange(newResult) {
    //do what you need with new result value here
  }
 }
 render(<Parent/>, document.getElementById('app'));

Child.jsx

constructor(props) {
    super(props);
    this.state = {
        result: 'logout'
    };
    this.login_action = this.login_action.bind(this);
    this.logout_action = this.logout_action.bind(this);

    }

    login_action(){
        this.setState({result: 'login'});
        this.props.onResultChange('login');
    }

    logout_action(){
        this.setState({result: 'logout'});
        this.props.onResultChange('logout');
    }

    render(){
        return(
        <div>
            <h1>{this.state.status}</h1>
            <button onClick={this.login}>Login</button>
            <button onClick={this.logout}>Logout</button>
        </div>
    )
}