有没有办法提取JSX元素的道具类型? [英] Is there a way to extract the type of the props of a JSX Element?
问题描述
我的意图是从给定的JSX元素中提取道具,有可能吗?
My intent is to extract the props out of a given JSX element, is it possible?
这几乎是我失败的尝试...预先感谢您的任何帮助;)
This was pretty much my failed attempt... Thanks in advance for any help ;)
function getComponentProps<T extends React.ReactElement>(element: T): ExtractProps<T>;
function Component({ name }: { name: string }) {
return <h1>{name}</h1>;
}
type ExtractProps<TComponentOrTProps> = TComponentOrTProps extends React.ComponentType<infer TProps>
? TProps
: TComponentOrTProps;
const componentProps = getComponentProps(<Component name="jon" />); //type is JSX.Element
推荐答案
在大多数情况下,您不能这样做.
For the most part, you can't do this.
在理论中, React.ReactElement
类型是通用的,其类型参数 P
取决于道具.因此,如果要使用强类型元素,则可以向后工作.
In theory, the React.ReactElement
type is generic with a type parameter P
that depends on the props. So if you were to have a strongly-typed element then you could work backwards.
type ElementProps<T extends React.ReactNode> = T extends React.ReactElement<infer P> ? P : never;
在 reality 中,如果通过 React.createElement
而不是JSX创建元素,则只会获得正确的道具类型.
In reality, you will only get a correct props type if you create your element through React.createElement
rather than JSX.
任何JSX元素<组件名称="John"/>
只会得到类型 JSX.Element
,该类型显然没有有关道具的信息,因此您不能从中返回到道具类型.
Any JSX element <Component name="John" />
just gets the type JSX.Element
which obviously has no information about the props so you cannot work backwards from that to a props type.
const e1 = React.createElement(
Component,
{ name: 'John' }
)
type P1 = ElementProps<typeof e1> // type: {name: string}
console.log(getElementProps(e1)); // will log {name: "John"}
const e2 = <Component name="John" />
type P2 = ElementProps<typeof e2> // type: any
console.log(getElementProps(e2)); // will log {name: "John"}
从另一个角度处理这种情况要容易得多.如果您的函数采用像 Component
或 div
这样的组件而不是解析的元素,则可以派生正确的props类型.您可以将 ComponentProps
实用程序类型用于功能和类组件,而将 JSX.IntrinsicElements
映射用于内置组件.
It is much easier to approach the situation from a different angle. You will be able to derive the correct props type if your function takes a component like Component
or div
rather than a resolved element. You can use the ComponentProps
utility type for function and class components and the JSX.IntrinsicElements
map for built-in ones.
这篇关于有没有办法提取JSX元素的道具类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!