typescript - 获取传入 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
我怎样才能做到这一点?提前致谢。
解决方案
使用您将使用的组件的道具创建一个泛型类型。
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'
。
推荐阅读
- c# - ASP.NET Core MVC - 从表单到控制器操作的无效输入
- javascript - 从 Safari 扩展向网站/标签添加元素
- dart - Flutter Snackbar 关闭监听器
- c# - 如何让一个方法采用不确定数量的不同类型的列表?
- java - 如何将 html 文件存储在 SQLite 数据库中?
- json - 反应原生 json 图像
- python - 如何使用对象比较函数反转 heapq 堆中元素的顺序?
- ios - Obj-c - 显示“使用 Apple Pay 支付”按钮?
- sql - 带有 like 的 Where 子句要注意 4 位数字
- android - 如何为 BottomNavigationView 设置键盘可访问性?