[英]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();
不是功能...谢谢!
谢谢!
登录名应该是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.