【发布时间】:2021-09-30 03:40:30
【问题描述】:
我正在尝试编写一个组件,它接受另一个组件的实例数组作为道具。该组件是MyComponent,它接受Title 的实例数组作为其参数之一。但是,我无法让 TypeScript 输入检查:
import * as React from "react";
type TitleProps = {
name: string;
};
function Title(props: TitleProps) {
return null;
}
type MyComponentProps = {
titles: Array<React.ReactElement<TitleProps>>;
}
function MyComponent({ titles }: MyComponentProps) {
return <div>{titles}</div>;
}
function OtherComponent(props: {}) { return null }
const shouldError = <MyComponent titles={[ <div/>, <OtherComponent/> ]} />;
const shouldNotError = <MyComponent titles={[ <Title name="hi"/>, <Title name="hi2"/>, ]} />;
如您所见,我可以将任何我想要的东西传递给 titles 属性,而不仅仅是 <Title/> 的实例。
【问题讨论】:
-
我希望操场在最后一行出错,因为我将
<div/>传递给titles,它应该是Title实例的数组,例如[<Title/>, ...].. -
@DavidGomes 我了解错误是什么,但该游乐场并没有为问题添加任何新内容。当您添加指向 Playground 的链接时,人们会期望他们可以在那里尝试。
-
我认为这个问题更多地与typescript处理JSX的方式有关,没有错误,因为任何元素都是JSX.Element,当我们使用react处理JSX时,它也是一个ReactElement。没有办法通过 JSX 标签来限制元素,因为本质上,它们是函数的结果,道具或标签不再重要。这个答案有更详细的解释:stackoverflow.com/a/59418019/10922948
-
PS 为什么将子组件作为道具传递而不是嵌套组件/使用 React 子组件?
标签: reactjs typescript