首页 > 解决方案 > 自动反应按下按钮

问题描述

在设置身份验证时,我遇到了一个问题,即只有通过按钮触发身份验证才能触发身份验证。

所以,我很想知道这是否是一种在 React 中自动触发按钮的 Onclick 事件的方法。

render() {
const { isAuthenticated } = this.props.auth;

return (
 <div>
   {
     !isAuthenticated() && (
      <Button
      bsStyle="primary"
      className="btn-margin"
      onClick={this.login.bind(this)}
    >
      Login
    </Button>
     )
   }
   { 
     isAuthenticated() && (
      <Button
      bsStyle="primary"
      className="btn-margin"
      onClick={this.logout.bind(this)}
    >
      Logout
    </Button>
     ) 
   }
 </div>
  );
  }

上面的代码是我的渲染方法,我想自动触发登录按钮!

提前谢谢各位!

标签: reactjsreact-router

解决方案


你不能这样做,JSX你需要使用componentWillReceieProps()

componentWillReceieProps(nextProps){
    if(nextProps.auth !== this.props.auth && this.props.auth){
        this.logout();
    }else if(nextProps.auth !== this.props.auth && !this.props.auth){
        this.login();
    }
}

推荐阅读