【问题标题】:Each child in a list should have a unique "key" prop. in react列表中的每个孩子都应该有一个唯一的“关键”道具。在反应
【发布时间】:2020-03-30 14:40:31
【问题描述】:

我有一个像下面这样的子组件

import React, { Component } from 'react';

class InputText extends Component  {
  render = () => {    
    return (
      <div className="form-group">
        <label htmlFor={this.props.id}>{this.props.label}</label>
        <input type={this.props.type} value={this.props.value} placeholder={this.props.placeholder} name={this.props.name} id={this.props.id} className= {"form-control "+ this.props.class} required={this.props.extraValue}/>
      </div>
    )
  }
}

export default InputText

我在下面的父组件中调用它

<InputText class="" placeholder="Email here..." type="email" name="email" onChange={this.handleChange} extraValue={true} label={[<span className="text-danger">*</span>, " Email"]} />

我收到如下错误

Warning: Each child in a list should have a unique "key" prop.

Check the render method of `InputText`. It was passed a child from Register. See https://fb.me for more information.
    in span (at Register.js:182)
    in InputText (at Register.js:182)                                  

【问题讨论】:

标签: reactjs key react-component


【解决方案1】:

作为数组传递的每个 JSX 元素都必须有一个唯一的 id。只需为 span 元素分配一些键。

label={[<span key={1} className="text-danger">*</span>, " Email"]}
            // ^^^^ key

但是我建议你将它作为两个单独的 props 传递,而不是作为数组传递。

label={'*'}
text={'Email'}

在你的组件内部:

<label htmlFor={this.props.id}>
   <span className='text-danger'>{this.props.label}</span>
   {this.props.text}
</label>

【讨论】:

  • 感谢@kind 用户。我没有数组。那么如何生成唯一 ID 呢?
  • @abuabu 实际上你有一个数组 - 你在一个数组中传递两个节点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-03
  • 1970-01-01
  • 1970-01-01
  • 2019-08-21
  • 2020-03-27
  • 1970-01-01
相关资源
最近更新 更多