我正在研究一个接受数据项列表的 React 组件,一个从数据项构造组件并将这些项格式化为表格的函数。代码看起来像这样:
export default class DataGrid extends React.Component{
constructor(props) {
super(props);
this.generateChild = item => this.props.template(item);
}
render () {
return tabulate (
this.props.data.map(this.generateChild),
this.props.cols
);
}
}
export function tabulate (components, cols)
{
return <table><tbody>{
collateRows (components, cols).map(cols =>
<tr>{cols.map(v =>
<td key={keyOf(v)}>{v}</td>)
}</tr>)
}</tbody></table>;
}
(其中collateRows
是将数据值分配到二维行和列数组中的函数)
我想知道的是,我如何编写keyOf
那里引用的函数:它需要生成一个标识符,该标识符对每个项目都是唯一的,但在对同一项目的调用之间保持一致。它还需要尽可能少地了解数据项本身,因为它旨在成为一个完全通用的组件,可用于任何合理的数据类型。
我所知道的是该template
属性是一个返回 React 组件的函数,并且该组件具有key
包含适当值的属性。但我似乎无法访问该属性(我得到undefined
一个警告,说我应该提供另一个具有相同值的道具,但是因为我希望能够将它与任何组件类型一起使用,我不看看这将如何工作......),那么我能做些什么呢?