React 在函数中绑定this并传参的几种方式

先看看为什么需要绑定this:

import React from 'react'

export default class BindThis extends React.Component {
    
    
  constructor(props) {
    
    
    super(props)
    this.state = {
    
    
      msg: '这是默认的MSG',
    }
  }
  render() {
    
    
    return (
      <div>
        <input
          type="button"
          value="绑定this并传参的方式"
          onClick={
    
    this.changeText}
        />
      </div>
    )
  }
  changeText(e) {
    
    
    this.setState({
    
    
      msg: e.target.value,
    })
  }
}

当点击按钮时,控制台会报错,因为changeText()中的this是undefined,无法获取setState()方法。因此我们需要在调用changeText()时明确的绑定this的引用。

下面看看绑定this的几种方式:

1. 函数定义使用箭头函数
changeText= (e) => {
    
    
    this.setState({
    
    
      msg: e.target.value,
    })
  }
2. bind()
<input type="button" value="绑定this并传参的方式2" onClick={
    
    this.changeMsg1.bind(this, '哈哈', '呵呵')} />

bind 的作用: 为前面的函数,修改函数内部的 this 指向,让 函数内部的this,指向 bind 参数列表中的 第一个参数.
bind 和 call/apply 之间的区别:.
1. call/apply 修改完this指向后,会立即调用前面的函数,但是 bind 只是修改this指向,并不会调用
2. 注意: bind 中的第一个参数,是用来修改 this 指向的,第一个参数后面的所有参数,都会当作将来调用 前面函数 时候的参数传递进去

3.在HTML绑定事件使用箭头函数
<input type="button" value="绑定this并传参的方式3" onClick={
    
    () => {
    
     this.changeMsg3('哈哈', '呵呵') }} />

猜你喜欢

转载自blog.csdn.net/weixin_43334673/article/details/111153151
今日推荐