我在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(); 不是一个函数..。谢谢!
谢谢!
发布于 2018-10-17 11:24:57
在这样的场景中使用redux更好,因为这使得组件之间的通信非常容易。否则,如果您想走艰苦的道路,那么创建一个父组件,它将包装登录和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
}
}https://stackoverflow.com/questions/52853420
复制相似问题