![](/img/trans.png)
[英]'this' context different for event handlers in function vs class react components
[英]why are we binding 'this' keyword for event handlers in react class components?
对于类组件中的事件处理程序,需要绑定(来自许多来源的信息)。 但是当控制台记录“this”关键字时,它会记录“context:undefined”(因为据我所知,类主体是严格的)。 如果我在事件处理程序中控制台记录 'this'(在本例中为 changeColor),它会记录 'context:{...}' 。
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = { color:green};
console.log(this); **// Toggle { ... context:undefined..... }**
this.changeColor = this.changeColor.bind(this);
}
changeColor() {
console.log(this); **// Toggle { ... context:{..} ..... }**
const newColor = this.state.color==green?yellow:green;
this.setState({color:newColor});
}
render() {
return (
<div style={{background:this.state.color}}>
<h1>
Change my color
</h1>
<button onClick={this.changeColor}>
Change color
</button>
</div>
);
}
}
如果 'this' 未定义,我们绑定的是什么?
changeColor
方法依赖于this
是组件的实例(所以当它访问this.state
它可以找到它)。
您正在将一个函数传递给事件侦听器,以便将其用作回调。
请参阅如何在回调中访问正确的 this? .
如果您不绑定this
值,它将在事件处理程序触发时在 DOM 元素的上下文中被调用。
这是一种古老的做事方式。 如果您不绑定,您将无法在诸如changeColor()
类的成员自定义方法中使用以下方法:
this.setState();
this.props.*;
this.state.*;
等等。 但是新的声明方式是使用() => {}
箭头函数。
您可以使用这种方式重写相同的代码:
class Toggle extends React.Component {
state = { color: green };
changeColor = () => {
const newColor = this.state.color == green ? yellow : green;
this.setState({ color: newColor });
};
render() {
return (
<div style={{ background: this.state.color }}>
<h1>Change my color</h1>
<button onClick={this.changeColor}>Change color</button>
</div>
);
}
}
这样,您就不需要constructor()
或将this
绑定到函数! 要进行另一次现实检查,请尝试以下操作:
import React, { Component } from "react";
export default class App extends Component {
NoArrowFunction() {
console.log(this);
}
ArrowFunction = () => {
console.log(this);
};
render() {
return <div>Check the Console!</div>;
}
}
this
应该是指其使用的范围或上下文。 在您的情况下,它指的是您的Component
。
如果 'this' 是 undefined ,我们绑定的是什么?
然后,您将绑定undefined
。
简而言之,您需要this
来访问事件处理程序中组件的属性。 如果您不需要访问它们,则不需要绑定this
。
考虑以下情况;
var obj = {
name: 'My Object',
myFunc: function() {
console.log('This object name is', this.name);
}
};
// When `this` is the `obj` itself.
obj.myFunc(); // Prints - "This object name is My Object"
// But, what if the function gets assigned to another variable / context? Which is what event listener does.
var anotherFunc = obj.myFunc;
anotherFunc(); // Prints - "This object name is"
// Since the function will print ANY context.name, we can also do it like;
var anotherFuncButBound = obj.myFunc.bind({
name: 'Something else'
});
anotherFuncButBound(); // Prints - "This object name is Something else"
// In your case, you're doing the following;
var anotherFunc = obj.myFunc.bind(obj);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.