gpt4 book ai didi

reactjs - 组件 which prop 必须是特定 React 元素的数组

转载 作者:行者123 更新时间:2023-12-04 04:32:06 26 4
gpt4 key购买 nike

我正在尝试编写一个组件,它接受另一个组件的实例数组作为 Prop 。该组件是 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 prop,不仅仅是 <Title/> 的实例.
TypeScript Playground URL

最佳答案

TypeScript 不是 Elixir 。 在许多情况下,保证 100% 类型安全需要在代码中引入额外的复杂性,或者根本不可能。您遇到过一种这样的情况。
an open GitHub issue on the subject of typing JSX elements .最好的办法是等待 TypeScript 为此引入特定的机制。
否则( from Matt McCutchen's answer ):

all JSX elements are hard-coded to have the JSX.Element type, so there's no way to accept certain JSX elements and not others. If you wanted that kind of checking, you would have to give up the JSX syntax, define your own element factory function that wraps React.createElement but returns different element types for different component types, and write calls to that factory function manually.


所以到目前为止,没有办法确保任何 JSX 元素的类型安全

关于reactjs - 组件 which prop 必须是特定 React 元素的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68491926/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com