render() {
const { type, id = this.id, className,
value = this.state.value, required, ...otherProps } = this.props;
return (
<input
id={id}
name={id}
className={className}
required={required}
aria-required={required}
type={type}
value={value}
onChange={this.handleChange}
{...otherProps}
/>
);
}
我试图将'id‘和'value’分别赋值给'this.id‘和'this.state.value’,但是这些值没有被赋值,而是从从this.props传递的值中得到赋值。
在用例中,componentWillMount()和handleChange()函数使用'pros.id‘和'props.value’来计算一些新的值,这些值将分配给'this.id‘和’the .state.value‘。因此,在上面的代码中,我需要从'this.id‘和'this.state.vale’分别获取'id‘和'value’。
发布于 2017-05-11 23:17:47
析构中的=
是指为非结构化对象中的键指定默认值(如果没有为其提供值)。例如:
const { key1 = 1, key2 = 2 } = { key1: 0 };
console.log(key1); // 0
console.log(key2); // 2
在这种情况下,可以分别对每个对象进行构造以初始化变量:
const { type, className, required, ...otherProps } = this.props;
const { id } = this;
const { value } = this.state;
如果要从id
中省略value
和value
,可以使用另一个名称对其进行重构。例如,我将它分配给名为_id
和_value
的变量。
const {
type, className, required,
id: _id, value: _value, // eslint-disable-line no-unused-vars
...otherProps
} = this.props;
const { id } = this;
const { value } = this.state;
发布于 2017-05-11 23:15:38
您正在将this.props
分解为变量,而您所使用的语法只在不存在this.id
时才会将this.props.id
分配给id
。在析构中使用=
是为了提供一个默认值,当该值不存在于析构对象中时(因此在本例中,this.id
只在不存在this.props.id
时才分配给id
)。
您应该从对象析构调用中删除id
。如果您想提供一个备用选项来使用道具中的id
,那么您可以这样做:
const id = this.id || this.props.id;
发布于 2017-05-11 23:21:28
你好像在找
const {type, id: this.id, className, value: this.state.value, required, ...otherProps} = this.props;
// ^ ^
:
分隔属性名称和赋值目标,=
用于默认初始化符。您的语法确实从this.id
获取了值,并在this.props
中没有id
属性时将其分配给了this.props
变量。
https://stackoverflow.com/questions/43931500
复制相似问题