简体   繁体   English

在组件之间传递状态-ReactJS

[英]Pass States between Components - ReactJS

I am trying to pass some states between components however the values are always undefined. 我试图在组件之间传递某些状态,但是值始终是不确定的。

I have a component called Home. 我有一个名为Home的组件。 When the user types in their email and password to login I want to pass those states to my other component ie So I have the users login information. 当用户键入他们的电子邮件和密码进行登录时,我想将这些状态传递给我的其他组件,即我拥有用户的登录信息。 However, the console.log statements show they are undefined. 但是,console.log语句显示它们是未定义的。

Home.js in render method 渲染方法中的Home.js

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

Below is what I have tried for HomePage.js 以下是我为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);
}

The above comes to undefined. 以上是未定义的。 In my Home.js, I can get the values I need but I can't seem to pass these to a different component. 在我的Home.js中,我可以获得所需的值,但似乎无法将其传递给其他组件。

You can access it by 您可以通过访问

this.props.signInEmail 
this.props.signInPassword

in your HomePage.js. 在您的HomePage.js中。

When you want to pass some data from parent to child component, they are called props. 当您要将某些数据从父组件传递到子组件时,它们称为道具。

Perhaps this help! 也许这有帮助! State and Props in React React中的状态和道具

You can recieve props from parent component by writing 您可以通过以下方式从父组件中接收道具

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

in the child component ie, HomePage.js in your case! 在子组件中,即HomePage.js!

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

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