React 中的this指向,获取方式.

// 需求.点击按钮的时候state里的arr++

export default class App extends React.Component {
  state = {
    arr: 18
  }
  handclick () {
  }
  render () {
    return (
      <>
        <button onClick={this.handclick}>按钮+1</button>
        <span>年龄:{this.state.arr}</span>
      </>
    )
  }
}

此时一般写法是在函数handclick 中输入

this.state.arr = this.state.arr + 1

但是在react中这里的this指向是undefined 所以需要以下方法获取到当前state.arr的值

方法1:

// 在点击按钮的时候调用这个函数.
// 函数触发以后return返回一个箭头函数.此时的箭头函数指向的是实例对象.
// 高阶函数.函数柯里化

export default class App extends React.Component {
  state = {
    arr: 18
  }
  handclick () {
    return () => {
      console.log(this.state.arr);//获得当前arr的值为18
    }
  }
  render () {
    return (
      <>
        <button onClick={this.handclick()}>按钮+1</button>
        <span>年龄:{this.state.arr}</span>
      </>
    )
  }
}

方法2: 推荐

缺点是无法传参,

// 通过赋值语句往实例上添加一个箭头函数

export default class App extends React.Component {
  state = {
    arr: 18
  }
  handclick = () => {
    console.log(this.state.arr);
  }
  render () {
    return (
      <>
        <button onClick={this.handclick}>按钮+1</button>
        <span>年龄:{this.state.arr}</span>
      </>
    )
  }
}

方法3.

xport default class App extends React.Component {
  constructor(){
    super()
    this.state = {
      arr: 18
    }
    this.handclick = this.handclick.bind(this)
  }
  handclick () {
    console.log(this);
  }
  render () {
    return (
      <>
        <button onClick={this.handclick}>按钮+1</button>
        <span>年龄:{this.state.arr}</span>
      </>
    )
  }
}

方法4

export default class App extends React.Component {
  state = {
    arr: 18
  }
  handclick () {
    console.log(this.state.arr);
  }
  render () {
    return (
      <>
        <button onClick={() => this.handclick()}>按钮+1</button>
        <span>年龄:{this.state.arr}</span>
      </>
    )
  }
}

方法5

bind所携带的this.指的就是实例,不代表参数.如果需要传参.可以继续添加.

如果需要匹配默认参数.比如event

则传  this.handclick.bind(this,a,b)

接handclick (a,b,e) {

     当e匹配不到参数传递的时候.就是默认的
    console.log(this);
  }

 
export default class App extends React.Component {
  state = {
    arr: 18
  }
  handclick () {
    console.log(this);
  }
  render () {
    return (
      <>
        <button onClick={this.handclick.bind(this)}>按钮+1</button>
        <span>年龄:{this.state.arr}</span>
      </>
    )
  }
}

猜你喜欢

转载自blog.csdn.net/wangyangzxc123/article/details/121748012