【react】类组件中的方法的this

由于changeWeather是作为onClick的回调,所以不是通过实例调用的,而是直接调用,且由于类里面的方法默认局部开启了严格模式,所以this指向undefined

<!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)     // this指向组件的实例对象
      }
      render() {
        console.log(this)  // render里面的this指向组件的实例对象,所以要想读取state,直接this.state
        return <h1 id='title' onClick= { this.changeWeather }>今天天气很{ this.state.isHot ? '炎热' : '凉爽' }</h1>
        // 此处this.changeWeather其实是从weather实例上沿着原型链去找changeWeather方法,然后调用,这算做直接调用,已经不是通过实例调用了
      }
      // changeWeather放在哪里了? —— 放在了类的原型对象上,供实例使用
      // 通过Weather实例调用changeWeather时,changeWeather中的this就是Weather实例
      changeWeather() {
        // 由于changeWeather是作为onClick的回调,所以不是通过实例调用的,而是直接调用,且由于类里面的方法默认局部开启了严格模式,所以this指向undefined
        console.log(this)   // undefined
        // console.log(this.state.isHot)
      }
    }
    ReactDOM.render(<Weather/>, document.getElementById('test'))

    // function changeWeather() { 
    //   console.log(this)   // undefined  因为babel会开启严格模式  但即使没有严格模式  this指向的也是window  我们无法在此处获取到实例的state中的值
    //   // 除非在最外层let that;  在contructor里面将this赋值给that this = that  但这样就很繁琐,如果有多个方法的时候,that也会被覆盖
    //   // 所以,正确写法应该是:将changeWeather方法放在类中去写
    // }
  </script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值