尝试从 this.props 赋值时,const{} 中的赋值不起作用

Assignment inside const{} is not working when trying to assign values from this.props

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' const 变量分别分配给 'this.id' 和 'this.state.value',但是没有分配值,而是这些值从 this.props.

传递的值中分配

我在一个用例中,其中 componentWillMount() 和 handleChange() 函数使用 'pros.id' 和 'props.value' 来计算一些将分配给 'this.id' 和 'this.state.value'。因此,在上面的代码中,我需要 'id' 和 'value' 分别取自 'this.id' 和 'this.state.vale'。

您正在将 this.props 解构为变量,您使用的语法只会在 this.props.id 不存在时将 this.id 分配给 id。在解构中使用 = 是为了在解构对象中不存在值时提供默认值(因此在此示例中 this.id 仅在 [=14= 时分配给 id ] 不存在)。

您应该从对象解构调用中删除 id。如果你想提供一个后备选项来使用 props 中的 id 那么你可以这样做:

const id = this.id || this.props.id;
解构中的

=表示分配默认值(如果没有为解构对象中的键提供值)。例如:

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;

如果你想从otherProps中省略idvalue,你可以用另一个名字解构它。例如,我将其分配给名称为 _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;

你好像在找

const {type, id: this.id, className, value: this.state.value, required, ...otherProps} = this.props;
//             ^                          ^

: 分隔 属性 名称和赋值目标,= 用于默认初始化程序。当 this.props.

中没有 id 属性 时,您的语法确实从 this.id 中获取值并将其分配给 id 变量