【问题标题】:Get type of props of a component passed in props获取传入 props 的组件的 props 类型
【发布时间】:2021-11-20 15:44:53
【问题描述】:

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

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

我想要的是像这样在 props 中获取组件的 props 类型:

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

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

【问题讨论】:

    标签: typescript react-native styled-components


    【解决方案1】:

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

    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&lt;Props&lt;P&gt;&gt; 类型,因为 P 出现在函数表达式之前,这使得 TypeScript 抱怨 cannot find name 'P'

    【讨论】:

    • 感谢您的回复,能否介绍一下如何将这个组件与 generic 一起使用?
    • 假设你有一个class X extends React.Component&lt;{ p: string }&gt;,你可以直接使用&lt;Component component={X} p='something'&gt;
    • 好的,让我检查一下。
    • 我已使用固定组件类型更新了答案并添加了示例。如果我之前的解决方案出错,请务必刷新页面。
    • 好的,我没有检查最后一个例子,不过会试试这个。
    猜你喜欢
    • 2019-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-11
    • 1970-01-01
    • 2018-12-01
    • 2020-05-17
    • 2020-02-04
    相关资源
    最近更新 更多