React可以使用React.createClass、ES6 classes、纯函数3种方式构建组件。使用React.createClass会自动绑定每个方法的this到当前组件,但使用ES6 classes或纯函数时,就要靠手动绑定this了。
bind(this)
Function.prototype.bind(thisArg [, arg1 [, arg2, …]]) 是ES5新增的函数扩展方法,bind()返回一个新的函数对象,该函数的this被绑定到thisArg上,并向事件处理器中传入参数
import React, {Component} from 'react'
class Greeter extends Component{
constructor (props) {
super(props)
this.state = {count: 0}
}
add (v) {
this.setState({
count:this.state.count+v
})
}
render () {
return (
<div>
<button onClick={this.add.bind(this,3)}>add</button>
</div>
)
}
}
构造函数内绑定
在构造函数 constructor 内绑定this,好处是仅需要绑定一次,避免每次渲染时都要重新绑定,函数在别处复用时也无需再次绑定
import React, {Component} from 'react'
class Greeter extends Component{
constructor (props) {
super(props)
this.state = {count: 0}
this.add=this.add.bind(this)
}
add () {
this.setState({
count:this.state.count+1
})
}
render () {
return (
<div>
<button onClick={this.add}>add</button>
</div>
)
}
}
箭头函数
箭头函数则会捕获其所在上下文的this值,作为自己的this值
1:
import React, {Component} from 'react'
class Greeter extends Component{
constructor (props) {
super(props)
this.state = {count: 0}
}
add () {
this.setState({
count:this.state.count+1
})
}
render () {
return (
<div>
<button onClick={()=>{this.add()}}>add</button>
</div>
)
}
}
2:
在Classes中直接赋值是ES7的写法,ES6并不支持,需要安装npm install --save-dev babel-preset-stage-2
//.babelrc
"presets":["react","env","stage-2"]
import React, {Component} from 'react'
class Greeter extends Component{
constructor (props) {
super(props)
this.state = {count: 0}
}
add=()=>{
this.setState({
count:this.state.count+1
})
}
render () {
return (
<div>
<button onClick={this.add}>add</button>
</div>
)
}
}
3:只用es6
import React, {Component} from 'react'
class Greeter extends Component{
constructor (props) {
super(props)
this.state = {count: 0}
this.add=()=>{
this.setState({
count:this.state.count+1
})
}
}
render () {
return (
<div>
<button onClick={this.add}>add</button>
</div>
)
}
}