我知道“this”关键字指的是当前/即时对象。在观看 React.js 教程时,我看到讲师将关键字与多个对象一起使用。代码如下所示:
class Counter extends Component {
state = {
count: 0
};
styles = {
fontSize: 10
};
render() {
return (
<div>
<h1 style={this.styles}>Hello</h1>
<span>{this.formatCount()}</span>
</div>
);
}
formatCount() {
const { count } = this.state;
return count === 0 ? "Zero" : count;
}
}
在 formatCount() 内部,为什么我们指的是 this.state
而不是 state.count
?另外,为什么不用 formatCount()
而不是 this.formatCount()
?老师一直说this
指的是当前对象,但他每次都在写this.objectname.properties
。这是为什么?不能只用objectname来区分object吗?
最佳答案
您的讲师正在使用 public field declarations在类里面。
如果它有助于您的理解,没有此功能的等效代码将是:
class Counter extends Component {
constructor() {
this.state = {
count: 0
};
this.styles = {
fontSize: 10
};
}
render() {
return (
<div>
<h1 style={this.styles}>Hello</h1>
<span>{this.formatCount()}</span>
</div>
);
}
formatCount() {
const { count } = this.state;
return count === 0 ? "Zero" : count;
}
}
换句话说,state = {...}
和 styles = {...}
只是声明 this.state
的简写和 this.styles
在构造方法中。
编辑:如果您想更好地理解 this
关键词,这里是another question you can reference .
关于javascript - "this"关键字与多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54975845/