【发布时间】:2017-12-20 14:38:18
【问题描述】:
我有以下嵌套组件:
<Table data={records}>
<TableColumn field="code">Code</TableColumn>
{columns.map((column, i) => (
<TableColumn key={column} field={column}>
{column}
</TableColumn>
))}
</Table>
我的Table 组件扩展了这个接口:
export interface TableProps {
data: any[];
children: React.ReactElement<TableColumnProps>[];
}
在该组件中,我使用以下函数遍历 Table 的子项(TableColumn 的实例):
getDefaultSortColumn() {
let col = this.props.children[0].props.field;
this.props.children.forEach((column: React.ReactElement<TableColumnProps>) => {
if (column.props.sortDefault) {
col = column.props.field;
}
});
return col as string;
}
当它执行时,我的期望是带有map() 的JSX 表达式已经执行,如果columns 中有4 个项目,那么在我的Table 中将有5 个TableColumn 元素作为直接子元素。相反,第二个元素实际上是一个元素数组。
为什么我的代码不只将TableColumn 元素作为直接子元素呈现给我的Table?
更新 似乎做以下工作:
getDefaultSortColumn() {
let col = this.props.children[0].props.field;
this.props.children.forEach((child: React.ReactElement<any>) => {
if (Array.isArray(child)) {
child.forEach((column: React.ReactElement<O3TableColumnProps>) => {
if (column.props.sortDefault) {
col = column.props.field;
}
});
}
else if (child.props.sortDefault) {
col = child.props.field;
}
});
return col as string;
}
但我不想像这样访问我的孩子,测试该项目是我想要的TableColumnProps 元素类型还是TableColumnProps 元素的数组。问题依然存在。
【问题讨论】:
标签: javascript reactjs typescript jsx