在ES6中,是否可以创建局部变量并直接引用它们,而不是在前面添加 this.
,例如this.name
.
例如,在下面的代码中,我该怎么做才能始终编写 {name}
而不是 {this.name}
。 (在变量前面添加 this.
有点麻烦!)
class User extend React.Component {
name = "Joe";
render() {
// is it possible to write {name} instead of {this.name}
return <div>{name}</div>
}
}
最佳答案
这可以通过 with
语句实现,但由于它与严格模式不兼容,因此在现代 JS 中没有任何值(value)。
否则无法执行此操作,并且由于 this.name
不应与 name
变量混淆,因此省略 this
将是一个错误。
如果 JSX 中的 this.name
影响可读性或者被多次使用,则可以对该属性进行解构:
render() {
const { name } = this;
return <div>{name}</div>
}
关于javascript - ES6 类 : how to omit "this" keyword,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50867834/