【问题标题】:spread operator in component react [duplicate]组件中的扩展运算符反应[重复]
【发布时间】:2017-09-08 09:37:47
【问题描述】:

在以下情况下使用扩展运算符时,我很难理解:

const renderField = ({input, label, type, meta: {touched, error, warning}}) => (
  <div>
    <label>{label}</label>
    <div>
      <input {...input} placeholder={label} type={type} />
      {touched &&
        ((error && <span>{error}</span>) ||
          (warning && <span>{warning}</span>))}
    </div>
  </div>
)

在这种情况下,它是否将所有道具设置为输入。道具名称

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

是的!当你传播input时,你的组件会自动获取它的属性。

假设你的input 是:

const input = {
  type: 'text',
  value: 'new value',
  placeholder: 'Type anything'
}

展开后,你渲染的组件将是:

<input type="text" placeholder="Type anything" value="new value" />

【讨论】:

    【解决方案2】:

    您在组件中使用JSX。如果您查看链接的文章,JSX 基本上只是 React.createElement 的一个包装器。每当您在 JSX 中使用大括号时,您实际上是在执行常规的 JavaScript 语句。

    因此,在您的情况下,实际发生的情况(简化)如下:

    React.createElement('input', {placeholder: label, ...input})
    

    如果您的input 变量包含其他道具,例如value,那么这些道具将根据spread operator specification 添加到原始道具对象({placeholder: label})。

    The spread syntax is also documented in the JSX explanation article.

    【讨论】:

      猜你喜欢
      • 2020-04-13
      • 2018-04-21
      • 1970-01-01
      • 2020-12-20
      • 2012-03-28
      • 1970-01-01
      • 2018-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多