gpt4 book ai didi

reactjs - 如何将动态 Prop 传递给接受对象联合作为其类型的 React 组件?

转载 作者:行者123 更新时间:2023-12-04 14:55:01 29 4
gpt4 key购买 nike

我想要一个组件来转发动态 Prop (我正在使用扩展运算符),这是我目前拥有的代码:

type Props = {
identifier: "YouTube";
attributes: { id: string };
} | {
identifier: "Figure";
attributes: { src: string };
};

const YouTube = ({ id }) => <p>{id}</p>;
const Figure = ({ src }) => <p>{src}</p>;

const Shortcode = ({ identifier, attributes }: Props): JSX.Element => {
switch (identifier) {
case "YouTube":
return <YouTube {...attributes} />;
case "Figure":
return <Figure {...attributes} />;
}
};

TypeScript 提示这个:

return <YouTube {...attributes} />;
// Type '{ id: string; } | { src: string; }' is not assignable to type 'IntrinsicAttributes & { id: any; }'.
// Property 'id' is missing in type '{ src: string; }' but required in type '{ id: any; }'.ts(2322)

return <Figure {...attributes} />;
// Type '{ id: string; } | { src: string; }' is not assignable to type 'IntrinsicAttributes & { src: any; }'.
// Property 'src' is missing in type '{ id: string; }' but required in type '{ src: any; }'.ts(2322)

如果我显式传递 props,TypeScript 会按预期运行:

<YouTube id="foo" />      // TS says this is ok
<YouTube wrong="props" /> // TS says this is missing the `id` prop

但是,我需要它来接受动态 Prop 。关于如何解决这个问题的任何想法?谢谢。

最佳答案

这是因为解构。 TS 不会将它们视为一个联盟的一部分。

为了让 TS 开心,就不要使用解构:

import React, { FC } from 'react';


type Props = {
identifier: "YouTube";
attributes: { id: string };
} | {
identifier: "Figure";
attributes: { src: string };
};

const YouTube: FC<{ id: string }> = ({ id }) => <p>{id}</p>;
const Figure: FC<{ src: string }> = ({ src }) => <p>{src}</p>;

const Shortcode = (props: Props): JSX.Element => {
switch (props.identifier) {
case "YouTube":
return <YouTube {...props.attributes} />; // ok
case "Figure":
return <Figure {...props.attributes} />; // ok
}
};

关于reactjs - 如何将动态 Prop 传递给接受对象联合作为其类型的 React 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68224988/

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