es6写法的类方法默认没有绑定this,不手动绑定this值为undefined。es6
所以讨论如下几种绑定方式。函数
class App extends Component { constructor (props) { super(props) this.state = { t: 't' } // this.bind1 = this.bind1.bind(this) 无参写法 this.bind1 = this.bind1.bind(this, this.state.t) } // 无参写法 // bind1 () { // console.log('bind1', this) // } bind1 (t, event) { console.log('bind1', this, t, event) } render () { return ( <div> <button onClick={this.bind1}>打印1</button> </div> ) } }
bind2 (t, event) { console.log('bind2', this, t, event) } render () { return ( <div> <button onClick={this.bind2.bind(this, this.state.t)}>打印2</button> </div> ) } // 无参写法同第一种
bind3 (t, event) { console.log('bind3', this, t, event) } render () { return ( <div> // <button onClick={() => this.bind3()}>打印3</button> 无参写法 <button onClick={(event) => this.bind3(this.state.t, event)}>打印3</button> </div> ) }
bind4 = () =>{ console.log('bind4', this) } render () { return ( <div> <button onClick={this.bind4}>打印4</button> // 带参须要使用第三种方法包一层箭头函数 </div> ) }
bind5(){ console.log('bind5', this) } render() { return ( <div> <button onClick={::this.bind5}></button> </div> ) }
优势:性能
只会生成一个方法实例;
而且绑定一次以后若是屡次用到这个方法也不须要再绑定。this
缺点:code
即便不用到state,也须要添加类构造函数来绑定this,代码量多;
添加参数要在构造函数中bind时指定,不在render中。console
优势:event
写法比较简单,当组件中没有state的时候就不须要添加类构造函数来绑定this。class
缺点:渲染
每一次调用的时候都会生成一个新的方法实例,所以对性能有影响;
当这个函数做为属性值传入低阶组件的时候,这些组件可能会进行额外的从新渲染,由于每一次都是新的方法实例做为的新的属性传递。构造函数
优势:
建立方法就绑定this,不须要在类构造函数中绑定,调用的时候不须要再做绑定;
结合了方法1、2、三的优势。
缺点:
带参就会和方法三相同,这样代码量就会比方法三多了。
方法一是官方推荐的绑定方式,也是性能最好的方式。
方法二和方法三会有性能影响,而且当方法做为属性传递给子组件的时候会引发从新渲染问题。
方法四和附加方法不作评论。
你们根据是否须要传参和具体状况选择适合本身的方法就好。
谢谢阅读。