react this绑定的几种方式

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>React</title>
  <script src="./lib/react-development.js"></script>
  <script src="./lib/react-dom-development.js"></script>
  <script src="./lib/babel-min.js"></script>
</head>


<body>
  <div id="app"></div>
</body>


<script type="text/babel">
  class App extends React.Component {
    //#region 什么是 class 的 fields ?
    // 在类中,可以这样写:thisName = 'White',这就是 es6 的 class 的 fields
    thisName = 'White'
    //#endregion

    constructor() {
      super()
      this.state = {
        count: 0
      }
      
      `绑定this:bind`
      this.btnClick_2 = this.btnClick_2.bind(this)
    }

    btnClick_1() {
      console.log('this=', this) // this= undefined
    }

    btnClick_2() {
      console.log('this=', this) // this指向`class App extends React.Component {}`这个组件实例
      this.setState({ count: this.state.count++ })
    }

    btnClick_3 = () => {
      console.log('this=', this) // this指向`class App extends React.Component {}`这个组件实例
      this.setState({ count: 3 })
    }

    btnClick_4() {
      console.log('this=', this) // this指向`class App extends React.Component {}`这个组件实例
      this.setState({ count: 4 })
    }

    render() {
      // render():render函数中的this,指向的就是当前组件实例

      return (
        <div>
          ` 
            这样写,获取的this,值是undefined,为什么呢?
            因为,btnClick_1函数并不是我们主动调用的,而是当button发生改变时,React内部调用了btnClick_1函数
            而它内部调用时,并不知道要如何绑定this
          `
          <button onClick={this.btnClick_1}>点击-1</button>

          `绑定this:bind`
          <button onClick={this.btnClick_2}>点击-2</button>

          `绑定this:es6的class fields`
          <button onClick={this.btnClick_3}>点击-3</button>

`          绑定this:直接传入一个箭头函数`
          <button onClick={() => this.btnClick_4()}>点击-4</button>

          <h3>当前计数:{this.state.count}</h3>
        </div>
      )
    }
  }


  const root = ReactDOM.createRoot(document.querySelector('#app'))
  root.render(<App />)

</script>
</html>


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值