gpt4 book ai didi

没有 React : Child Types 的 typescript 和 JSX

转载 作者:行者123 更新时间:2023-12-04 08:23:43 28 4
gpt4 key购买 nike

所以我觉得我错过了一些明显的东西。我已经在非 React 上下文中阅读了有关 JSX 的文档,但我没有看到我做错了什么。考虑以下代码:

/** @jsx pragma */

function pragma(node: any, props: any, ...children: any[]) {
return node;
}

declare namespace JSX {
type Element = string;
interface ElementChildrenAttribute {
children: {}; // specify children name to use
}
}

interface PropsType {
children: string;
name: string;
}

export const Prop = (props: PropsType) => {};

const foo = <Prop name="foo">hello</Prop>;
我得到的错误(在最后一行)是:
Property 'children' is missing in type '{ name: string; }' but required in type 'PropsType'.
我可以“纠正”这个:
const foo = <Prop name="foo" children="bye">hello</Prop>;
但我预计 hello将被分配为 children .我不应该指定一个明确的 children 属性(property) , 对?我在这里缺少什么?我希望原件没问题(不会产生错误),因为 children字段应填写字符串值 "hello"在那种情况下(并且不需要我添加 children Prop ?!?)。
我在这里缺少什么? JSX 是否还有其他类型/字段?命名空间我需要在这里填写才能使这项工作?
澄清 :我在这里担心的是 TypeScript 没有将字符串“hello”分配给 child 。如果这样做了,一切都会好起来的。因此,这似乎不是我的 prop 类型的问题,因为我在重新声明 JSX 命名空间时遗漏了一些东西,它告诉编译器如何处理我的“自定义”JSX。
另外,我确实不需要 children在我的 Prop 中。但我当然被允许而且我绝对想这样做,因为这允许我缩小类型。正是出于这个原因,这绝对是允许的(请参阅第二段 here )。在这里添加它不会创建一个新的 Prop ,它只是改进了 JSX.ElementChildrenAttribute 中定义的任何内容。 .

最佳答案

在 React 中,您可以使用类型 PropsWithChildren<T> .这是 React 使用的,但您可以自己制作并用 JSX 替换 React 细节。
这应该可以处理所有使用案例的 Children 可以是什么。

type Children = JSX.Element[] | JSX.Element | string | number | boolean | null | undefined;

type PropsWithChildren<P> = P & {
children?: Children;
}

type PropsType = {
name: string;
}

export const Bar = ({ name, children }: PropsWithChildren<PropsType>) => (
<div>
<p>{name}</p>
<div>{children}</div>
</div>
);
我测试过,所有这些都不会抛出类型错误。
export const ElementArray = () => (
<Bar name="Foo">
<div>Hello</div>
<div>World</div>
</Bar>
)

export const Element = () => (
<Bar name="Foo">
<div>Hello World</div>
</Bar>
)

export const String = () => (
<Bar name="Foo">Hello World</Bar>
)

export const Number = () => (
<Bar name="Foo">{43110}</Bar>
)

export const Boolean = () => (
<Bar name="Foo">{true}</Bar>
)

export const Null = () => (
<Bar name="Foo">{null}</Bar>
)

export const Undefined = () => (
<Bar name="Foo" />
)
此外,您可以创建自己的 FC (功能组件)类型使用 PropsWithChildren并像在 React 中一样使用它。
type FC<P = {}> = {
(props: PropsWithChildren<P>): JSX.Element;
}

// usage
export const FooBar: FC<PropsType> = ({ name, children }) => (
<div>
<p>{name}</p>
<p>{children}</p>
</div>
);

关于没有 React : Child Types 的 typescript 和 JSX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65375997/

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