如何在 React/JSX 中手动创建的数组中设置密钥?

How do I set the key in a manually created array in React/JSX?

我正在构建一个基于几种不同状态的工具栏。一切正常,我只能按下所需的(当时)按钮,一切都很好。

因为它是一个数组,React 想要它在每个元素上的宝贵键。然而,在每个推送点手动设置它们似乎不太灵活,因为我需要在添加更多项目时手动更新。

我尝试了一个简单的地图 post 创建(参见 _.map 行)但是 item.key 是只读的。

有没有办法根据数组索引或类似的方法自动分配键?

var toolbar = null;
if(!this.state.loading) {
    toolbar = [];
    if(this.state.conditionOne) {
        toolbar.push(<a onClick={this.toggleOne}>Close Section One</a>);
    } else {
        toolbar.push(<a onClick={this.toggleOne}>Show Section One</a>);
    }
    if(this.state.conditionTwo) {
        toolbar.push((
            <div>
                <a onClick={this.otherAction}>Other Action</a>
                <a onClick={this.toggleTwo}>Close Section Two</a>
            </div>
        );
    } else {
        toolbar.push(<a onClick={this.toggleTwo}>Show Section Two</a>);
    }

    _.map(toolbar, (item, i) => { item.key = i; });
}

// Later
return (
    Stuff and things
    {toolbar}
);

我相信你现在已经找到了一个好方法。正如昨天评论中所写,根据按钮的行为手动分配按键可能还不错。

但是,如果它们太多(或者只是为了将密钥的创建保存在一个明确定义的位置),您可以集中计算。我已经设置了一个小 Codepen 来说明它。

class App extends React.Component { 
  // (1) Helper method
  applyMenuItemProps(label) {
    return {
      label: label,
      key: _.snakeCase(_.escape(label))
    };
  }

  render() {
    // (2) Stateless component
    const MenuItem = (props) => <li><a href="#">{ props.label }</a></li>;

    // (3) Using the Spread operator to apply the properties
    let menuItems = [
      <MenuItem {...this.applyMenuItemProps("Hello World")} />,
      <MenuItem {...this.applyMenuItemProps("Ham and Eggs")} />
    ];

    return (
      <div>
        <p><strong>Render with keys</strong></p>
        { menuItems }
      </div>
    );
  }
}

(1) 是 returns 标签和计算键的辅助方法。在这种情况下,我使用 Lodash's/Underscore 的 snakeCaseescape 来计算基于标签的字符串(当然只有在没有两个项目时才有效同一数组中的相同标签)。

(2)用的是React的stateless components (docs),我开始很喜欢。如果它们应该是可重用的,它们可以进入一个单独的模块,但我喜欢它们的一件事是它们不一定需要一个单独的文件,因此样板文件可以最少。

(3) 使用 Javascript 的扩展运算符 (ES2015) 将 applyMenuItemProps() 返回的对象的属性应用为 <MenuItem/> 元素的属性。

Codepen 还应用了 onClick 处理程序。我把它留在这里是因为它与集中计算密钥没有太大关系。希望它对您有所帮助,并且您喜欢使用 React。 :)