<!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>
react this绑定的几种方式
最新推荐文章于 2024-09-26 10:39:16 发布