react绑定this的三种方式

作者: MJ 分类: react 发布时间: 2018-11-07 13:29

第一种:

class App extends Component {
  constructor(props){
    super(props);
    this.state = {
      show:true
    }
    this.showFun = this.showFun.bind(this)
  }
  showFun(){
    this.setState({
      show:!this.state.show
    })
  }
  render() {
    return (
      <div>
        {this.state.show ? 'show' : 'hide'}
        <button onClick={this.showFun}>click</button>
      </div>
		);
  }
}

第二种:

class App extends Component {
  constructor(props){
    super(props);
    this.state = {
      show:true
    }
  }
  showFun(){
    this.setState({
      show:!this.state.show
    })
  }
  render() {
    return (
      <div>
        {this.state.show ? 'show' : 'hide'}
        <button onClick={this.showFun.bind(this)}>click</button>
      </div>
		);
  }
}

第三种:

class App extends Component {
  constructor(props){
    super(props);
    this.state = {
      show:true
    }
  }
  showFun = ()=>{
    this.setState({
      show:!this.state.show
    })
  }
  render() {
    return (
      <div>
        {this.state.show ? 'show' : 'hide'}
        <button onClick={this.showFun}>click</button>
      </div>
		);
  }
}

 

 

欢迎关注小程序,感谢您的支持!

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

发表评论

邮箱地址不会被公开。 必填项已用*标注