有没有办法让我的子组件了解父组件的 prop 类型?
我不想将它们硬编码到孩子中,因为孩子将被多个具有稍微不同道具的父母使用。
一个简化的例子:
// Parent.tsx
import React, {ReactElement} from "react";
interface Row {
id: string;
name: string;
tags: string[];
}
const Parent = (): ReactElement => {
const rows: Row[] = [
{
id: "1",
name: "Foo",
tags: ["new"],
},
{
id: "1",
name: "Bar",
tags: ["new", "sale"],
},
];
const formatRow = (row: Row): ReactElement => (
<tr key={row.id}>
<td>{row.id}</td>
<td>{row.name}</td>
<td>{row.tags.map(tag => <strong>{tag}</strong>)}</td>
</tr>
);
return <Child formatRow={formatRow} rows={rows} />;
};
export default Parent;
// Child.tsx
import React, {ReactElement} from "react";
const Child = ({formatRow, rows}): ReactElement => {
const columnCount = Object.keys(rows[0]).length;
return (
<table>
<tbody>
{rows.map(row => formatRow(row))}
</tbody>
<tfoot>
<tr>
<td colSpan={columnCount}>Footer</td>
</tr>
</tfoot>
</table>
);
};
export default Child;
那么也可能有另一个父母,Parent2
用这个形状来实现它自己的Row
:
// Parent2.tsx
interface Row {
id: string;
count: number;
}
const Parent2 = (): ReactElement => {
// similar code to `Parent` here
};
export default Parent2;
我不知道如何让Child
组件知道formatRow
期望一个Row
并返回一个ReactElement
,而 rows 是一个数组Row
物体?
我认为泛型可能是答案,但我对此的了解非常有限,因此无论是泛型还是其他任何帮助,我们都会表示赞赏。