[英]Preserve array index inside react clone child loop
我有一个奇怪的问题,就是在循环和克隆反应孩子时无法保留索引。 这是有问题的代码:
// Table Body component
const DataBody = ({
resource,
children,
ids,
data,
...rest
}) => (
<tbody {...rest}>
{ids.map((id, rowIndex) => (
<TableRow key={id}>
{React.Children.map(children, (field, index) => {
return (
<Cell
key={`${id}-${field.props.source || index}`}
record={data[id]}
{...{ field, index, resource }}
/>
)
})}
</TableRow>
))}
</tbody>
)
// Table Cell component
const Cell = ({ classes, field, index, record, resource, theme, ...rest }) => {
return (
<td className={mapToCSSModule(classes, theme)} {...rest}>
{React.cloneElement(field, { record, resource, index })}
</td>
)
}
// Table data component
const IndexField = ({
format,
index,
tag: Tag = 'span',
...props
}) => {
const no = index + 1
return <Tag {...props}>{format ? format(no) : no}</Tag>
}
现在的问题是,IndexField内的index始终为0,但是在Cell中,它的值还可以,就像我们在循环/闭包中迷路一样,该循环/闭包始终返回所传递变量的最后一个值。 有没有一种干净的方法来优雅地处理此问题?
编辑:添加了通过数据循环的主要组件,请注意,这是向下流的版本(原始版本可以正常工作,只有不起作用的是索引)。
由于某种原因,rowIndex可以正常工作,因此我实现了该功能,而不是子索引。这是代码:
// Table Body component
const DataBody = ({
resource,
children,
ids,
data,
startingNo, // First item index (data is paged on the server)
...rest
}) => (
<tbody {...rest}>
{ids.map((id, rowIndex) => (
<TableRow key={id}>
{React.Children.map(children, (field, index) => {
return (
<Cell
key={`${id}-${field.props.source || index}`}
index={startingNo + rowIndex}
{...{ field, resource }}
/>
)
})}
</TableRow>
))}
</tbody>
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.