【react】解决类组件中的方法的this指向问题

bind可以改变this的指向,在构造器中使用bind将类的实例对象给到方法中的this,jsx片段中调用bind返回的新函数即可

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>解决类组件中的方法的this指向问题</title>
</head>
<body>
  <div id="test"></div>

  <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
  <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

  <script type="text/babel">
    class Weather extends React.Component {
      // 想要对类里的实例对象的值进行操作,就要用到构造器
      constructor(props) {
        super(props)    // 继承的类,写了构造器的话,必须写super
        // 改变state
        this.state = { isHot: false, wind: '风' }   
        console.log(this, 'constructor')     // this指向组件的实例对象
        this.newWeather = this.changeWeather.bind(this)     // 此处是使用bind将changeWeather方法中的this指向改为组件的实例对象   然后赋值给newWeather方法   因为bind返回的是一个新函数  需要重新调用
      }
      render() {
        console.log(this, 'render')  // render里面的this指向组件的实例对象,所以要想读取state,直接this.state
        return <h1 id='title' onClick= { this.newWeather }>今天天气很{ this.state.isHot ? '炎热' : '凉爽' }</h1>
      }
      changeWeather() {
        console.log(this, 'changeWeather')   
      }
    }
    ReactDOM.render(<Weather/>, document.getElementById('test'))
  </script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值