簡體   English   中英

在組件之間傳遞狀態-ReactJS

[英]Pass States between Components - 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中,我可以獲得所需的值,但似乎無法將其傳遞給其他組件。

您可以通過訪問

this.props.signInEmail 
this.props.signInPassword

在您的HomePage.js中。

當您要將某些數據從父組件傳遞到子組件時,它們稱為道具。

也許這有幫助! React中的狀態和道具

您可以通過以下方式從父組件中接收道具

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

在子組件中,即HomePage.js!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM