首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >获取传入props的组件的props类型

获取传入props的组件的props类型
EN

Stack Overflow用户
提问于 2021-09-28 15:23:15
回答 1查看 38关注 0票数 0

我想创建一个React Native组件,其类型如下所示,它接受一个组件并对其应用一些样式:

代码语言:javascript
复制
interface Props {
  component: any;
 }
 const Component: React.FC<Props> = ({component}) => {
  const Styled = styled(component)`
    background-color: red;
  `;
 }

我想要的是像这样在props中传递组件的prop类型:

代码语言:javascript
复制
<Component component={Pressable} onPress={() => console.log("sds")} /> //Should accept this props
<Component component={Image} source={{}} /> //Should accept Image props

我如何才能做到这一点?提前谢谢。

EN

回答 1

Stack Overflow用户

发布于 2021-09-29 16:55:31

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

代码语言:javascript
复制
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'

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69364448

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档