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>