实例化后将 React 键道具设置为动态组件数组



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

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.

所以我的问题是下一个:在实例化这些组件后,是否可以为数组中的每个组件设置键 prop?

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>
);
}

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

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

在您的情况下,您应该renderPaginationButton()返回一个已经放入key=prop 的<Link>元素。

最新更新