在React中使用class定义组件时如果不注意this的指向问题,会带来一些麻烦。
绑定this主要有下面两种方法:
1. bind()
在class中定义函数,然后在构造方法中使用bind()绑定当前的组件对象。
1class MyComponent extends React.Component { 2 constructor(props) { 3 super(props) ; 4 this.handleClick = this.handleClick.bind(this) ; 5 } 6 handleClick() { 7 //... 8 } 9 render() { 10 return ( 11 <div> 12 <button onClick={this.handleClick}>点击</button> 13 </div> 14 ) 15 } 16}
2. 箭头函数
箭头函数中的this指向定义函数定义时所在的执行环境。而不是运行时所在的环境。
1class MyComponent extends React.Component { 2 constructor(props) { 3 super(props) ; 4 5 } 6 handleClick = () => { 7 //... 8 } 9 render() { 10 return ( 11 <div> 12 <button onClick={this.handleClick}>点击</button> 13 </div> 14 ) 15 } 16}
组件中,哪些函数需要绑定当前组件对象呢,主要有:
1. 事件处理函数
2. 作为自定义属性传入子组件的函数
1class MyComponent extends React.Component { 2 constructor(props) { 3 super(props) ; 4 5 } 6 7 commentAdd = () => { 8 //... 9 } 10 render() { 11 return ( 12 <div> 13 <CommentList CommentAdd={this.commentAdd} /> 14 </div> 15 ) 16 } 17}
CommentList是一个子组件,从父组件中传入了一个函数作为这个子组件的自定义属性。
3. 异步操作的回调函数
1class MyComponent extends React.Component { 2 constructor(props) { 3 super(props) ; 4 this.state = { 5 6 title: 'hello world' 7 } 8 9 } 10 11 12 componentDidMount() { 13 setTimeout((function() { 14 this.setState({ 15 title: '你好,世界' 16 }) 17 }).bind(this), 1000) 18 } 19 20 render() { 21 return ( 22 <div> 23 <h1>{this.state.title}</h1> 24 </div> 25 ) 26 } 27} 28ReactDOM.render(<MyComponent/>, document.querySelector('#app'))
setTimeout()的第一个参数是一个回调函数。此时这个回调函数需要绑定当前的组件对象,因为回调函数内需要组件的一些方法和属性。
总结
凡是组件内自定义的函数,都要绑定组件对象。而且最好使用箭头函数定义函数。这样函数内部的this直接指向当前的组件对象。
组件中不能使用立即执行的函数。