Reactjs this.setState不是函数错误

vee*_*ran 3 reactjs

我是新手React js,我不知道下面的代码有什么问题,但我得到的setState不是函数错误.请帮我解决这个问题.

class AppBarLayout extends React.Component {
  constructor(props) {
      super(props);

      this.state = {
        visibleSideBar:true,
        slide:""
      }
  }
  showProfile(){

    this.setState({
        slide:'slide'
    });
    console.log(this.state.slide);
  }
  render(){
    return(
            <div>
        <header>
          <NavBar show={this.showProfile}/>
          <Profile slide={this.state.slide} />
        </header>
      </div>
    );
  }
}
export default AppBarLayout;
Run Code Online (Sandbox Code Playgroud)

Del*_*ite 14

您需要this.showProfile在组件构造函数中绑定

this.showProfile = this.showProfile.bind(this)

关于React doc 的处理事件页面的更多细节:https://facebook.github.io/react/docs/handling-events.html


Cés*_*rca 8

如果你不喜欢绑定构造函数中的每个函数,可以扩展Delapouite的答案,你可以使用箭头函数自动绑定到正确的上下文.

例如:

class AppBarLayout extends React.Component {
  constructor(props) {
      super(props);

      this.state = {
        visibleSideBar:true,
        slide:""
      }
  }

  // Now showProfile is an arrow function
  showProfile = () => {
    this.setState({
        slide:'slide'
    });
    console.log(this.state.slide);
  }

  render(){
    return(
      <div>
        <header>
          <NavBar show={this.showProfile}/>
          <Profile slide={this.state.slide}/>
        </header>
      </div>
    );
  }
}
export default AppBarLayout;
Run Code Online (Sandbox Code Playgroud)