在 jQuery 中的回调函数中使用 es6 的写法该怎样绑定 this ?
普通写法
componentDidMount() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data})
}.bind(this)
})
}
如果这样写改怎样绑定 this ?
componentDidMount() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success(data) {
this.setState({data: data})
}
})
}
或许是我想多了?
确实想多了,
createClass
写法完全不用操绑定的心,如果是class
就把要传给子组件的函数在构造函数里绑定下,不过我一般都是直接用箭头函数如onClick={() => { this.add() }}