React绑定this的三种方式

前端之家收集整理的这篇文章主要介绍了React绑定this的三种方式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

React可以使用React.createClass、ES6 classes、纯函数3种方式构建组件。使用React.createClass会自动绑定每个方法的this到当前组件,但使用ES6 classes或纯函数时,就要靠手动绑定this了。接下来介绍React中三种绑定this的方法

bind()

Function.prototype.bind(thisArg [,arg1 [,arg2,…]])是ES5新增的函数扩展方法,bind()返回一个新的函数对象,该函数的this被绑定到thisArg上,并向事件处理器中传入参数

  1. import React,{Component} from 'react'
  2.  
  3. class Test extends React.Component {
  4. constructor (props) {
  5. super(props)
  6. this.state = {message: 'Allo!'}
  7. }
  8.  
  9. handleClick (name,e) {
  10. console.log(this.state.message + name)
  11. }
  12.  
  13. render () {
  14. return (
  15. <div>
  16. <button onClick={ this.handleClick.bind(this,'赵四') }>Say Hello</button>
  17. </div>
  18. )
  19. }
  20. }

要注意的是,跟在this(或其他对象)后面的参数,之后它们会被插入到目标函数的参数列表的开始位置,传递给绑定函数的参数会跟在它们的后面。

构造函数内绑定

在构造函数constructor内绑定this,好处是仅需要绑定一次,避免每次渲染时都要重新绑定,函数在别处复用时也无需再次绑定

  1. import React,{Component} from 'react'
  2.  
  3. class Test extends React.Component {
  4. constructor (props) {
  5. super(props)
  6. this.state = {message: 'Allo!'}
  7. this.handleClick = this.handleClick.bind(this)
  8. }
  9.  
  10. handleClick (e) {
  11. console.log(this.state.message)
  12. }
  13.  
  14. render () {
  15. return (
  16. <div>
  17. <button onClick={ this.handleClick }>Say Hello</button>
  18. </div>
  19. )
  20. }
  21. }

箭头函数

箭头函数则会捕获其所在上下文的this值,作为自己的this值,使用箭头函数就不用担心函数内的this不是指向组件内部了。可以按下面这种方式使用箭头函数

  1. class Test extends React.Component {
  2. constructor (props) {
  3. super(props)
  4. this.state = {message: 'Allo!'}
  5. }
  6.  
  7. handleClick (e) {
  8. console.log(this.state.message)
  9. }
  10.  
  11. render () {
  12. return (
  13. <div>
  14. <button onClick={ ()=>{ this.handleClick() } }>Say Hello</button>
  15. </div>
  16. )
  17. }
  18. }

这种方式有个小问题,因为箭头函数总是匿名的,如果你打算移除监听事件,可以改用以下方式:

  1. class Test extends React.Component {
  2. constructor (props) {
  3. super(props)
  4. this.state = {message: 'Allo!'}
  5. }
  6.  
  7. handleClick = (e) => {
  8. console.log(this.state.message)
  9. }
  10.  
  11. render () {
  12. return (
  13. <div>
  14. <button onClick={ this.handleClick }>Say Hello</button>
  15. </div>
  16. )
  17. }
  18. }

不过,在Classes中直接赋值是ES7的写法,ES6并不支持,只用ES6的话可以用下面写法:

  1. class Test extends React.Component {
  2. constructor (props) {
  3. super(props)
  4. this.state = {message: 'Allo!'}
  5. this.handleClick = (e) => {
  6. console.log(this.state.message)
  7. }
  8. }
  9.  
  10. render () {
  11. return (
  12. <div>
  13. <button onClick={ this.handleClick }>Say Hello</button>
  14. </div>
  15. )
  16. }
  17. }

三种方法都能实现this的绑定,至于用哪种方式还跟着自己的习惯来。

》》 更多干货 》》

参考

猜你在找的React相关文章