赞助

在JSX事件函数方法中的 this,默认不会绑定 this指向。如果你忘记绑定,当你调用这个函数的时候 this 的值为 undefined。所以使用时一定要绑定好this的指向。

  • 构造方法中绑定

constructor(props){

    super(props)

    // 在构造方法中指定this指向  <button onClick={this.fun()}>按钮</button>

    this.fun = this.fun.bind(this)

}

import React, { Component } from 'react'

export default class Userthis extends Component {

  // 方案解决this指向问题
  constructor(props) {
    super(props);
    // 手动绑定this的指向
    // this.fn = this.fn.bind(this)
  }



  render() {
    return (
      <div>
        {/* <button onClick={this.fn}>获取父组传过来的数据</button> */}

        {/* 方案2 在绑定方法中使用bind */}
        {/* <button onClick={this.fn.bind(this)}>获取父组传过来的数据</button> */}

        {/* 方案3 箭头函数绑定 */}
        {/* <button onClick={() => this.fn()}>获取父组传过来的数据</button> */}

        {/* 方案4 在绑定实现的方法中定义使用箭头函数 */}
        <button onClick={this.fn}>获取父组传过来的数据</button>

      </div>
    )
  }
  // 方案4
  fn = () => {
    console.log(this.props)
  }

  
  /* fn() {
    console.log(this.props)
  } */
}

 

posted on 2021-04-16 15:41  Tsunami黄嵩粟  阅读(46)  评论(0)    收藏  举报