Mar*_*ria 2 javascript ecmascript-6 reactjs babeljs ecmascript-next
在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>
}
}
Run Code Online (Sandbox Code Playgroud)
这是可能的with语句,但由于它与严格模式不兼容,它在现代JS中没有价值.
除此之外没有办法做到这一点,因为this.name不应该与name变量混淆,省略this将是一个错误.
如果this.name在JSX中影响可读性或多次使用,则可以对属性进行解构:
render() {
const { name } = this;
return <div>{name}</div>
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
469 次 |
| 最近记录: |