【问题标题】:React: send keyed children to a component. Keys always nullReact:将键控子级发送到组件。键始终为空
【发布时间】:2016-03-27 19:38:42
【问题描述】:

我在将键控元素发送到子元素时遇到问题,该子元素将通过键过滤这些子元素。这个想法是通过键将处理程序映射到子项,处理程序将切换键以进行过滤。我知道使用索引作为键是一种反模式,但是这里发生了什么?我总是收到错误"Warning: Each child in an array or iterator should have a unique "key" prop.

render: function() { return ( <Frame> <Frame> <Navbar isLoggedIn={true} handlers={this.handlers}> {this.props.children.map(function(child, i) { return ( <button onClick={this.handlers[i]}>{child.props.text || 'Checkout item ' + i}</button> ) }.bind(this))} </Navbar> </Frame> {this.props.isLoading ? <Loading /> : <Filter filter={function(child) { return String(this.props.displayed) === child.key; }.bind(this)}> {this.props.children.map(function(child, i) { return (<div key={i}><child /></div>) })} </Filter>} </Frame> ) }

function Filter (props) { return ( <div> {Array.isArray(props) ? props.children.filter(function(child) { return props.filter(child); }) : props.children} </div> ) };

【问题讨论】:

    标签: reactjs redux react-redux


    【解决方案1】:

    您需要将一个键传递给任何被迭代的 DOM 元素。你在&lt;button&gt; 中不见了。

    <Navbar isLoggedIn={true} handlers={this.handlers}>
      {this.props.children.map(function(child, i) {
        return (
          <button key={i} onClick={this.handlers[i]}>{child.props.text || 'Checkout item ' + i}</button>
        )
      }.bind(this))}
    </Navbar>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-01
      • 1970-01-01
      • 2015-09-12
      • 1970-01-01
      • 2022-08-16
      • 1970-01-01
      • 1970-01-01
      • 2018-12-27
      相关资源
      最近更新 更多