首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >来自另一个组件的Set状态响应js。

来自另一个组件的Set状态响应js。
EN

Stack Overflow用户
提问于 2018-10-17 11:07:30
回答 4查看 6.5K关注 0票数 0

我在index.js中有以下结构:

代码语言:javascript
运行
复制
<MyAppBar // + properties/>
 <Route path={path} component={Login}/>

MyAppBar.js

代码语言:javascript
运行
复制
 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 (所有组件),但是它说

代码语言:javascript
运行
复制
MyAppBar.handleLogin(); 

不是一个函数..。谢谢!

谢谢!

EN

Stack Overflow用户

发布于 2018-10-17 11:24:57

在这样的场景中使用redux更好,因为这使得组件之间的通信非常容易。否则,如果您想走艰苦的道路,那么创建一个父组件,它将包装登录和MyAppBar。

代码语言:javascript
运行
复制
  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方法

代码语言:javascript
运行
复制
   this.props.setLoginState(true);

在myappbar组件中,使用isLoggedIn支柱有条件地呈现

代码语言:javascript
运行
复制
   renderLogin(){
     if(this.props.isLoggedIn){ 
          // return loggedin jsx
     }else{
         return the alternative
     }
   }
票数 0
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52853420

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档