键入Reaction组件工厂函数 [英] Typing a React Component Factory Function
本文介绍了键入Reaction组件工厂函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定类型
type EnumerableComponentFactory = <C, I>(config: {
Container: React.ComponentType<C>;
Item: React.ComponentType<I>;
}) => React.FC<{ items: I[] }>;
使用以下实现
const Enumerable: EnumerableComponentFactory =
({ Container, Item }) =>
({ items }) =>
(
<Container>
{items.map((props, index) => (
<Item key={index} {...props} />
))}
</Container>
);
和预期用途
const UnorderedList = Enumerable({
Container: ({ children }) => <ul>{children}</ul>,
Item: ({ title }: { title: string }) => <li>{title}</li>,
});
<UnorderedList items=[{title: "Something"}] />
我发现以下打字错误
Type '{ children: Element[]; }' is not assignable to type 'C'.
'C' could be instantiated with an arbitrary type which could be unrelated to '{ children: Element[]; }'.ts(2322)
这就引出了我的问题:我需要设置什么类型的约束来解决此错误?
我已尝试按如下方式更改类型:
type EnumerableComponentFactory = <C extends { children?: Element[] }, I>(config: {
Container: ComponentType<C>;
Item: ComponentType<I>;
}) => (props: { items: I[] }) => ReturnType<FC<I>>;
但这会产生一个更加隐晦的错误消息,为简洁起见,我将省略它。
附注:该函数本身实际上执行的正是预期的操作。只是编译器出错了。
推荐答案
我能够更改您的代码以使其工作,同时还接受要传递给容器的其他道具:
type EnumerableComponentFactory = <C, I>(config: {
Container: React.ComponentType<C & { children: React.ReactNode[] }>;
Item: React.ComponentType<I>;
}) => React.ComponentType<C & { items: I[] }>;
const Enumerable: EnumerableComponentFactory = ({ Container, Item }) => (
props
) => (
<Container {...props}>
{props.items.map((props, index) => (
<Item key={index} {...props} />
))}
</Container>
);
这允许这样做:
const ContainerWithBorder: React.ComponentType<{ color: string }> = (props) => (
<div style={{ border: `2px solid ${props.color}` }}>
<ul>{props.children}</ul>
</div>
);
const ComplexList = Enumerable({
Container: ContainerWithBorder,
Item: ({ title }: { title: string }) => <li>{title}</li>
});
<ComplexList items={[{ title: "Something" }]} color="red" />
ComplexList
组件附带color
属性的类型/智能感知。
包含ComplexList
原始示例的游乐场here。
这篇关于键入Reaction组件工厂函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文