use*_*274 5 javascript ecmascript-6 reactjs
我正在学习反应,我正在按照快速入门指南,在主题提升状态我找到了计算器组件
class Calculator extends React.Component {
constructor(props) {
super(props);
...
this.state = {scale: 'c', temperature: ''}
}
handleCelsiusChange(temperature) {
this.setState({scale: 'c', temperature})
}
handleFahrenheitChange(temperature) {
this.setState({scale: 'f', temperature});
}
render() {
...
return (
<div>
...
</div>
)
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是this.setState({scale: 'c', temperature})我期待的这句话this.setState({scale: 'c', temperature: temperature}).
这个temperature分配有些反应是辛糖吗?你能解释一下为什么会这样吗?
谢谢
{scale: 'f', temperature}基本上是一种Property value shorthand语法{scale: 'f', temperature: temperature},
因此,在JavaScript中ES6/ES2015,如果要定义一个对象,其键的名称与作为属性传入的变量具有相同的名称,则可以使用简写并简单地传递键名.
请查看此文档以获取详细信息
使用此语法时需要注意的一件重要事情是,JS引擎在包含范围内查找具有相同名称的变量.
如果找到,则将该变量的值分配给该属性.
如果没有找到,ReferenceError则抛出a.值得注意的是,transpilers如果找不到变量,则不会在编译时抛出错误,而是声明一个具有not-found变量名称的对象.
但是,当代码运行时,您仍将获得ReferenceError该变量不存在的情况.
| 归档时间: |
|
| 查看次数: |
62 次 |
| 最近记录: |