我想创建一个React Native组件,其类型如下所示,它接受一个组件并对其应用一些样式:
interface Props {
component: any;
}
const Component: React.FC<Props> = ({component}) => {
const Styled = styled(component)`
background-color: red;
`;
}我想要的是像这样在props中传递组件的prop类型:
<Component component={Pressable} onPress={() => console.log("sds")} /> //Should accept this props
<Component component={Image} source={{}} /> //Should accept Image props我如何才能做到这一点?提前谢谢。
发布于 2021-09-29 16:55:31
使用您将使用的组件的道具创建泛型类型。
type Props<P> = P & {
component: (new (props: P) => React.Component<P>) | React.FC<P>;
};
function Component<P>(props: Props<P>): JSX.Element {
return <props.component {...props}></props.component>;
}
class X extends React.Component<{ p: string }> {}
const Y: React.FC<{ p: number }> = props => <></>;
<Component component={X} p="something"></Component>;
<Component component={Y} p={1}></Component>;不幸的是,你将不能使用React.FC<Props<P>>类型,因为P出现在函数表达式之前,这使得TypeScript抱怨cannot find name 'P'。
https://stackoverflow.com/questions/69364448
复制相似问题