问题:类组件中,事件处理函数中 this 为 undefined。
class App extends React.Component{
constructor(){
super()
this.state = {
msg: 'lxx'
}
}
handleBtnClick(){
// 此时 this 为 undefined
console.log(this.state.msg);
}
render(){
return (
<button onClick={this.handleBtnClick}>按钮</button>
)
}
}
方法一:使用 bind 绑定 this
class App extends React.Component{
constructor(){
super()
this.state = {
msg: 'lxx'
}
}
handleBtnClick(){
console.log(this.state.msg);
}
render(){
// 将 render 中的 this 绑定给 handleBtnClick 方法
return (
<button onClick={this.handleBtnClick.bind(this)}>按钮</button>
<button onClick={this.handleBtnClick.bind(this)}>按钮</button>
<button onClick={this.handleBtnClick.bind(this)}>按钮</button>
)
}
}
在构造函数中进行一次性绑定 this
class App extends React.Component{
constructor(){
super()
this.state = {
msg: 'lxx'
}
this.handleBtnClick = this.handleBtnClick.bind(this)
}
handleBtnClick(){
console.log(this.state.msg);
}
render(){
return (
<button onClick={this.handleBtnClick}>按钮</button>
<button onClick={this.handleBtnClick}>按钮</button>
<button onClick={this.handleBtnClick}>按钮</button>
)
}
}
方法二:使用箭头函数赋值成员变量
class App extends React.Component{
constructor(){
super()
this.state = {
msg: 'lxx'
}
}
// 将箭头函数赋值给成员变量
// 箭头函数中没有this,向上层作用域中查找
handleBtnClick = () => {
console.log(this.state.msg);
}
render(){
return (
<button onClick={this.handleBtnClick}>按钮</button>
)
}
}
方法三:事件处理函数直接给个箭头函数
class App extends React.Component{
constructor(){
super()
this.state = {
msg: 'lxx'
}
}
handleBtnClick () {
console.log(this.state.msg);
}
render(){
return (
<button onClick={() => this.handleBtnClick()}>按钮</button>
)
}
}