React - 事件绑定this
在 React 中,this
的绑定是一个常见问题,尤其在类组件中使用事件处理函数时。JavaScript 中的 bind
函数用于设置函数调用时 this
的值。
bind
函数的作用
bind()
方法创建一个新的函数,当被调用时,其this
关键字被设置为提供的值。- 另外,
bind
还可以预设参数,这常用于部分应用的场景。
在 React 中的应用
在使用 React 的类组件时,事件处理函数通常需要正确绑定 this
,以确保 this
指向组件实例。以下是一种常见的实现方式:
1. 在构造函数中绑定
import React, { Component } from "react";
export default class Test extends Component{
constructor(props) {
super(props)
// 初始化状态
this.state = { isHot: false }
// 解决 changeWeather中 this 指向问题
this.changeWeather = this.changeWeather.bind(this)
}
render() {
// 读取状态
const {isHot} = this.state
return (
<h1 onClick={this.changeWeather}>今天天气很{isHot?'炎热':'凉爽'}</h1>
)
}
changeWeather() {
// changeWeather 放在 Weather 的原型对象上,供实例使用
// 由于 changeWeather 是作为 onClick 的回调,所以不是通过实例调用的,是直接调用
// 类中的方法默认开启了局部的严格模式,所以 changeWeather 中的this 是 undefined
// 获取原来的 isHot 值
const isHot = this.state.isHot
// 严重注意:状态必须通过 setState 进行更新
this.setState({isHot:!isHot})
}
}
2. 使用箭头函数
import React, { Component } from "react";
export default class Test extends Component{
constructor(props) {
super(props)
// 初始化状态
this.state = { isHot: false }
// 解决 changeWeather中 this 指向问题
// this.changeWeather = this.changeWeather.bind(this)
}
render() {
// 读取状态
const {isHot} = this.state
return (
<h1 onClick={this.changeWeather}>今天天气很{isHot?'炎热':'凉爽'}</h1>
)
}
changeWeather = () => {
// changeWeather 放在 Weather 的原型对象上,供实例使用
// 由于 changeWeather 是作为 onClick 的回调,所以不是通过实例调用的,是直接调用
// 类中的方法默认开启了局部的严格模式,所以 changeWeather 中的this 是 undefined
// 获取原来的 isHot 值
const isHot = this.state.isHot
// 严重注意:状态必须通过 setState 进行更新
this.setState({isHot:!isHot})
}
}
总结
bind
方法用于明确设置函数调用时this
的值,避免在事件处理程序中this
指向错误。- 在 React 中,有多种方式处理
this
的绑定,主要包括在构造函数中绑定和使用箭头函数。 - 对于大型组件或频繁更新的组件,推荐在构造函数中绑定
this
,或者使用类属性定义箭头函数,以减少不必要的性能开销。
代码简写形式:
import React, { Component } from "react";
export default class Test extends Component{
// 初始化状态
state = { isHot: false,wind:'微风' }
render() {
const {isHot,wind} = this.state
return (
<h1 onClick={() => this.changeWeather()}>今天天气很{isHot ? '炎热' : '凉爽'},{wind}</h1>
)
}
changeWeather=()=>{
const isHot = this.state.isHot
this.setState({isHot:!isHot})
}
}