gpt4 book ai didi

reactjs - 用于选择特定组件的对象文字 react / typescript

转载 作者:行者123 更新时间:2023-12-04 07:38:30 24 4
gpt4 key购买 nike

是否可以使用带有枚举的对象文字来返回 Typescript/React 中的不同组件?
如果没有,为什么这种模式不起作用?


enum ItemType {
TASK,
NOTE,
}

function NoteComponent(props: { type: ItemType.NOTE }) {
return <div />;
}

function TaskComponent(props: { type: ItemType.TASK }) {
return <div />;
}

function getComp(type: ItemType): typeof NoteComponent | typeof TaskComponent {
return {
[ItemType.NOTE]: NoteComponent,
[ItemType.TASK]: TaskComponent,
}[type];
}

const noteProps = { type: ItemType.NOTE };
const taskProps = { type: ItemType.TASK };

function App() {
const Comp1 = getComp(noteProps.type);
const Comp2 = getComp(taskProps.type);

return (
<>
<Comp1 {...noteProps} />
{/**
Type '{ type: ItemType; }' is not assignable to type 'never'.
The intersection 'IntrinsicAttributes & { type: ItemType.NOTE; }
& { type: ItemType.TASK; }' was reduced to 'never' because
property 'type' has conflicting types in some constituents.
ts(2322)
*/}
<Comp2 {...taskProps} />
{/**
Type '{ type: ItemType; }' is not assignable to type 'never'.
The intersection 'IntrinsicAttributes & { type: ItemType.NOTE; }
& { type: ItemType.TASK; }' was reduced to 'never' because
property 'type' has conflicting types in some constituents.
ts(2322)
*/}
</>
);
}
更新:
怎么设置 ItemType.NOTE as const当值从 API 返回而不是硬编码时?
const apiResponse = [
{ type: ItemType.NOTE, ...noteSpecificProps },
{ type: ItemType.TASK ...taskSpecificProps },
];


apiResponse.map(item => {
const Comp = getComp(noteProps.type);

return <Comp {...item} />;
});

最佳答案

  • getComp函数应该根据提供的类型(而不是联合)返回特定的组件。这可以通过重载或泛型来实现。
  • 在对象字面量 { type: ItemType.NOTE }type扩大到 ItemType , 以防止这种情况 as const assertion可以使用。
  • const componentMap = {
    [ItemType.NOTE]: NoteComponent,
    [ItemType.TASK]: TaskComponent,
    }

    function getComp<T extends ItemType>(type: T) {
    return componentMap[type];
    }

    const noteProps = { type: ItemType.NOTE } as const;
    const taskProps = { type: ItemType.TASK } as const;

    function App() {
    const Comp1 = getComp(noteProps.type);
    const Comp2 = getComp(taskProps.type);

    return (
    <>
    <Comp1 {...noteProps} />
    <Comp2 {...taskProps} />
    </>
    );
    }
    Playground

    关于reactjs - 用于选择特定组件的对象文字 react / typescript ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67618519/

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