簡體   English   中英

從另一個組件React js設置狀態

[英]Set state from another component React js

我在index.js中具有以下結構:

<MyAppBar // + properties/>
 <Route path={path} component={Login}/>

MyAppBar.js

 class MyAppBar extends React.Component {

state = {
  auth: false,
  anchorElement: null
};

handleLogin(){
  this.setState({auth:true});
}

//another code
//end component

export default withStyles(styles)(MyAppBar)

我想從Login組件操作處理程序(即handleLogin )內將MyAppBar狀態auth標志更新為true ,但是我不知道如何。

我已經嘗試在“ 登錄”頁面上導入MyAppBar (所有組件),但是它說

MyAppBar.handleLogin(); 

不是功能...謝謝!

謝謝!

我認為對於這種簡單的范例,您無需經歷設置redux的所有麻煩(我喜歡Redux,但有時我們不必使用它)

這是在新context實現它的方法。

編輯React掛鈎

它非常簡單易用。 在此處檢查讓我知道是否不清楚。

登錄名應該是MyAppBar的子級組件。 然后,您可以將handleLogin函數作為登錄的道具。

您應該使用REDUX。

主要是因為它使您擁有任何組件都可以讀取或可以與其同步的狀態。

我很少使用react的state / setState。

在大多數情況下,redux狀態可以更改/監視。

在這種情況下最好使用redux,因為這使得組件之間的通信非常容易。 否則,如果您想努力工作,則創建一個父組件,它將包裝login和MyAppBar。

  class ParentComp extends Component{
      constructor(props){ 
         super(props);
         this.state={
             isLoggedIn:false
         };
        this.setLoginState=this.setLoginState.bind(this);
      }
      setLoginState(value){
          this.setState({isLoggedIn:value});
      }

       render(){
         return(<div>
                   <MyAppBar isLoggedIn={this.state.isLoggedIn} />
               <Route path={path} render={props=><Login {..props} setLoginState={this.setLoginState}/>}/>
                </div>);
       }
  }

在您的LoginComponent中調用setLoginState方法

   this.props.setLoginState(true);

並在myappbar組件中使用isLoggedIn屬性有條件地進行渲染

   renderLogin(){
     if(this.props.isLoggedIn){ 
          // return loggedin jsx
     }else{
         return the alternative
     }
   }

暫無
暫無

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

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