React.createClass()

React提供了React.createClass方法来创建组件,React会自动绑定this到函数中去,所以不需要手动绑定

React.createClass({
  getInitialState: function() {
    return {
      liked: false
    }
  },
  handleChange: function(e) {
    this.setState({
      liked: !this.state.liked
    })
  },
  render: function() {
    return (
      <div>
        <h3>{ this.state.liked ? 'like': 'unlike' }</h3>
        <button onClick={ this.handleChange }>click</button>
      </div>
    )
  }
})

bind(this)

目前流行用class来创建组件,babel编译,所以react内部没有帮我们自动绑定this的指向,需要手动绑定

class Code extends React.Component {
  state = {
    liked: false // true
  }
  handleChange (e) {
    this.setState({
      liked: !this.state.liked
    })
  }
  render() {
    return (
      <div>
        <h3>{ this.state.liked ? 'like': 'unlike' }</h3>
        <button onClick={ this.handleChange.bind(this) }>click</button>
      </div>
    )
  }
}

上面的绑定this虽然是能够改变this的指向,但是会损耗性能,应为每次渲染组件的时候都调用了一次绑定操作,虽然性能没多大影响,但是尽量避免,最好的方法是在构造函数中执行绑定操作

class Code extends React.Component {
  constructor(props) {
    super(props);
    // 在构造函数绑定this
    this.handleChange = this.handleChange.bind(this);
  }
  state = {
    liked: true
  }
  handleChange (e) {
    this.setState({
      liked: !this.state.liked
    })
  }
  render() {
    return (
      <div>
        <h3>{ this.state.liked ? 'like': 'unlike' }</h3>
        <button onClick={ this.handleChange }>click</button>
      </div>
    )
  }
}

箭头函数

最后如果嫌弃每次都在构造函数绑定this麻烦的话,在定义相关函数的时候可以使用箭头函数来实现默认this指向

class Code extends React.Component {
  state = {
    liked: true
  }
  handleChange = () => {
    this.setState({
      liked: !this.state.liked
    })
  }
  render() {
    return (
      <div>
        <h3>{ this.state.liked ? 'like': 'unlike' }</h3>
        <button onClick={ this.handleChange }>click</button>
      </div>
    )
  }
}

对比三种方法,其实最后一种方法是最好的,避免了每次都要在构造函数手动绑定this和性能的损耗,而且通俗易懂,少些代码,减少打包体积

本文为原创,未经授权,禁止任何媒体或个人自媒体转载
商业侵权必究,如需授权请联系[email protected]
标签: Javascript React