You can't create a functional component with a type annotation and make it generic. So this will NOT work as T
is not defined and you can't define it on the variable level:
const CollapsableDataList : React.FunctionComponent<IProps<T>> = p => { /*...*/ }
You can however skip the type annotation, and make the function generic and type props
explicitly.
import * as React from 'react';
import { render } from 'react-dom';
interface IProps<T> {
collapsed: boolean;
listOfData: T[];
displayData: (data: T, index: number) => React.ReactNode;
}
const CollapsableDataList = <T extends object>(props: IProps<T> & { children?: ReactNode }) => {
if (!props.collapsed) {
return <span>total: {props.listOfData.length}</span>
} else {
return (
<>
{
props.listOfData.map(props.displayData)
}
</>
)
}
}
render(
<CollapsableDataList
collapsed={false}
listOfData={[{a: 1, b: 2}, {a: 3, c: 4}]}
displayData={(data, index) => (<span key={index}>{data.a + (data.b || 0)}</span>)}
/>,
document.getElementById('root'),
)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…