实例化后将React key prop设置为动态组件数组

时间:2018-10-15 21:05:14

标签: javascript reactjs

我有一个方法可以返回完全不同的组件数组:

renderComponents() {
  const children = [];
  children.push(this.renderComponent1());
  children.push(this.renderComponent2());
  if (something) {
    children.push(this.renderComponent3());
  }

  return children;
}

但是,当然我遇到了一个错误Each child in an array or iterator should have a unique "key" prop.。我试图像这样设置密钥:

children.forEach((child, i) => {
  Object.defineProperty(child.props, 'key', { value: i });
});

但是事实证明,React阻止了道具的扩展,所以我收到了Cannot define property key, object is not extensible

所以我的下一个问题是:是否可以在实例化数组中的每个组件之后为它们设置关键道具?

UPD:接下来是真实的代码(它以类似[1]...[5][6][7][8][9]...[100]的范围呈现分页):

  renderPaginationButton(page) {
    const { query, currentPage } = this.props;

    return (
      <Link
        className={classNames(styles.link, { [styles.active]: page === currentPage })}
        to={routes.searchUrl({ ...query, page })}
      >
        {page}
      </Link>
    );
  }

  renderPaginationSeparator() {
    return (
      <div className={styles.separator}>...</div>
    );
  }

  renderPaginationRange(from, amount) {
    const { pagesCount } = this.props;
    const result = [];

    for (let i = Math.max(from, 1); i < Math.min(from + amount, pagesCount); i++) {
      result.push(this.renderPaginationButton(i));
    }

    return result;
  }

  renderPagination() {
    const { currentPage, pagesCount } = this.props;

    if (pagesCount <= 1) {
      return;
    }

    const children = this.renderPaginationRange(currentPage - 2, 5);

    if (currentPage > 4) {
      children.unshift(
        this.renderPaginationButton(1),
        this.renderPaginationSeparator()
      );
    }

    if (pagesCount - currentPage > 4) {
      children.push(
        this.renderPaginationSeparator(),
        this.renderPaginationButton(pagesCount)
      );
    }

    return (
      <div className={styles.pagination}>
        {children}
      </div>
    );
  }

1 个答案:

答案 0 :(得分:1)

要直接回答您的问题,您可以使用React.cloneElement将道具添加到已实例化的组件上。

但这不是您在这种情况下应该做的。

对于您而言,您应该有renderPaginationButton()来返回一个<Link>元素,其中已经放置了key=个道具。