1、在构造函数初始化时,constructor中使用bind绑定this,
这样做的好处是,避免每次渲染时都要重新绑定
import React, {
Component} from 'react'
class Test extends React.Component {
constructor (props) {
super(props)
this.state = {
message: 'Allo!'}
//在构造函数中绑定this
this.handleClick = this.handleClick.bind(this)
}
handleClick (e) {
console.log(this.state.message)
}
render () {
return (
<div>
<button onClick={
this.handleClick }>Say Hello</button>
</div>
)}
}
2、在render函数内通过bind绑定
是这样的话,每次渲染都需要重新绑定
import React, {
Component} from 'react'
class Test extends React.Component {
constructor (props) {
super(props)
this.state = {
message: 'Allo!'}
}
handleClick (name, e) {
console.log(this.state.message + name)
}
//在render函数中绑定
render () {
return (
<div>
<button onClick={
this.handleClick.bind(this, '赵四') }>Say Hello</button>
</div>
)
}
}
3、在render函数中,调用方法的位置包裹一层箭头函数,
因为箭头函数的this指向箭头函数定义的时候其所处作用域的this,而箭头函数在render函数中定义,render函数this始终指向组件实例,所以箭头函数的this也指向组件实例。
class Test extends React.Component {
constructor (props) {
super(props)
this.state = {
message: 'Allo!'}
}
handleClick (e) {
console.log(this.state.message)
}
//通过箭头函数绑定this
render () {
return (
<div>
<button onClick={
()=>{
this.handleClick() } }>Say Hello</button>
</div>
)
}
4、属性初始化器语法
简单来说,定义变量,这个变量是个方法
缺点:仅限于执行函数无需入参的情况
class Test extends React.Component {
handleClick = () => {
}
render () {
return (
<div>
<button onClick={
this.handleClick }>Say Hello</button>
</div>
)
}
}
作者:易冷zzz
链接:https://www.jianshu.com/p/b69d12747dd0
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。