首页 > 解决方案 > 获取传入 props 的组件的 props 类型

问题描述

我想用这样的类型创建一个 React Native 组件,它需要一个组件并对其应用一些样式:

interface Props {
  component: any;
 }
 const Component: React.FC<Props> = ({component}) => {
  const Styled = styled(component)`
    background-color: red;
  `;
 }

我想要的是像这样获取在道具中传递的组件的道具类型:

<Component component={Pressable} onPress={() => console.log("sds")} /> //Should accept this props
<Component component={Image} source={{}} /> //Should accept Image props

我怎样才能做到这一点?提前致谢。

标签: typescriptreact-nativestyled-components

解决方案


使用您将使用的组件的道具创建一个泛型类型。

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'


推荐阅读