我正在学习 React,我正在关注 quick start guide , 在话题Lifting State Up我找到了计算器组件
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>
)
}
}
我的问题是关于这句话 this.setState({scale: 'c', temperature})
在这里我期待 this.setState({scale: 'c', temperature:温度})
.
这个 temperature
赋值是不是某种 react sintax 糖?你能解释一下为什么会这样吗?
谢谢
最佳答案
{scale: 'f', temperature}
基本上是 {scale: 'f', temperature: temperature} 的
,Property value shorthand
语法
所以在使用 ES6/ES2015
的 JavaScript 中,如果你想定义一个对象,其键与作为属性传入的变量同名,你可以使用简写并简单地传递键姓名。
检查这个 doc 详情
使用此语法时需要注意的重要一点是,JS 引擎会在包含范围内查找具有相同名称的变量。
如果找到,则将该变量的值分配给该属性。
如果未找到,则抛出 ReferenceError
。值得注意的是,如果未找到变量,转译器
不会在编译时抛出错误,而是会声明一个具有未找到变量名称的对象。
但是,当代码运行时,您仍然会得到 ReferenceError
,因为变量不存在。
关于javascript - 使用变量作为键和值创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48309649/