gpt4 book ai didi

reactjs - 在 Typescript 中 react 子组件

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

我们有一些复杂的组件组合,我在使它们类型安全时遇到了麻烦。根据下面的代码,我希望 Typescript 能够为 Menu.Item 提供类型。或 Menu.Link ,但它不是出于某种原因,它们被推断为“任何”(当您将其包装在 JSX 中时,它会被细化为 JSX.Element<any>。知道为什么会发生这种情况吗?

import * as React from 'react';

type RootFunctionComponent<OwnProps, SubComponents> = React.FunctionComponent<OwnProps> & SubComponents;

interface ItemProps {
text: string;
};

interface LinkProps {
href: string;
}

const Item: React.FunctionComponent<ItemProps> = props => <div {...props} />;
const Link: React.FunctionComponent<LinkProps> = props => <div {...props} />;

interface MenuSubComponents {
Item: React.FunctionComponent<;
Link: typeof Link;
}

const Menu: React.FunctionComponent<{}, MenuSubComponents> & MenuSubComponents = props => <div {...props} />

Menu.Item = Item;
Menu.Link = Link;


const Test: React.FunctionComponent<{}> = () => {
return <>
<Menu>
<Menu.Item text={false} />
<Menu.Link />
</Menu>
</>
}


结果:

the resulting any type

最佳答案

问题在于菜单类型定义:

React.FC<{}, MenuSubComponents>

正确的用法是:
React.FC<MenuSubComponents>

你可以在这里看到这个: https://codesandbox.io/s/condescending-lamarr-xjkcw

关于reactjs - 在 Typescript 中 react 子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56952879/

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