在组件之间传递状态-ReactJS

时间:2018-11-23 14:53:28

标签: javascript reactjs

我正在尝试在组件之间传递某些状态,但是值始终未定义。

我有一个叫做Home的组件。当用户输入其电子邮件地址和密码进行登录时,我想将这些状态传递给我的其他组件,即我拥有用户的登录信息。但是,console.log语句显示它们是未定义的。

渲染方法中的Home.js

return (
  <div>
    <HomePage signInEmail={this.state.signInEmail} signInPassword={this.state.signInPassword}/>
    <p>Account</p>
    <button onClick={this.logout}>Logout</button>
  </div>
);

以下是我为HomePage.js尝试过的内容

constructor(props) {
    super(props);
       this.state = {
        noResp: ''

    }
}

componentDidMount() {
    console.log('Component Mounted!');
    console.log('this.props.signInEmail  ' + this.props.signInEmail );
    console.log('this.props.signInPassword: ' + this.props.signInPassword);
}

以上未定义。在我的Home.js中,我可以获得所需的值,但似乎无法将其传递给其他组件。

1 个答案:

答案 0 :(得分:0)

您可以通过以下方式访问它

this.props.signInEmail 
this.props.signInPassword

在您的HomePage.js中。

当您要将某些数据从父组件传递到子组件时,它们称为道具。

也许有帮助! State and Props in React

您可以通过书写从父组件中获取道具

class HomePage extends React.Component{
    constructor(props){
         super(props);
}
render(){
    return(//THE JSX you wanna return)
 }
}

在子组件中,例如HomePage.js!