Chr*_*ong 31 typescript reactjs
我正在尝试利用最近添加的对TypeScript编译器中的子类型输入和@ types/react的支持,但很难.我正在使用TypeScript版本2.3.4.
说我有这样的代码:
interface TabbedViewProps {children?: Tab[]}
export class TabbedView extends React.Component<TabbedViewProps, undefined> {
  render(): JSX.Element {
    return <div>TabbedView</div>;
  }
}
interface TabProps {name: string}
export class Tab extends React.Component<TabProps, undefined> {
  render(): JSX.Element {
    return <div>Tab</div>
  }
}
当我尝试使用这些组件时:
return <TabbedView>
  <Tab name="Creatures">
    <div>Creatures!</div>
  </Tab>
  <Tab name="Combat">
    <div>Combat!</div>
  </Tab>
</TabbedView>;
我收到如下错误:
ERROR in ./src/typescript/PlayerView.tsx
(27,12): error TS2322: Type '{ children: Element[]; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<TabbedView> & Readonly<{ children?: ReactNode; }> ...'.
  Type '{ children: Element[]; }' is not assignable to type 'Readonly<TabbedViewProps>'.
    Types of property 'children' are incompatible.
      Type 'Element[]' is not assignable to type 'Tab[] | undefined'.
        Type 'Element[]' is not assignable to type 'Tab[]'.
          Type 'Element' is not assignable to type 'Tab'.
            Property 'render' is missing in type 'Element'.
它似乎正在推断孩子的类型,Element[]而不是Tab[]即使这是我正在使用的唯一类型的孩子.
编辑:限制子道具的界面,而不是直接限制子组件的类型也没关系,因为我需要做的就是从子组件中拉出一些特定的道具.
Pie*_*rry 20
您应该尝试像这样设置接口TabbedViewProps的子项
interface TabbedViewProps { children?: React.ReactElement<TabProps>[] }
这里的想法不是告诉你TabProps有一个数组TabbedView,而是告诉你Tab他有一个TabbedView特定道具阵列.在你的情况下element.
编辑(thx到Matei):
interface TabbedViewProps {
    children?: React.ReactElement<TabProps>[] | React.ReactElement<TabProps>
}
编辑2:事实证明这种方法可以防止警告,但根据评论TabProps未正确检查.
Dan*_*ger 15
已经作为指针,声明TabbedView.children为:
children: React.ReactElement<TabProps> | React.ReactElement<TabProps>[];
将摆脱错误,但不会正确地对孩子进行类型检查。也就是说,您仍然可以传递除TabPropsto以外的子项TabbedView而不会出现任何错误,因此这也是有效的:
return (
  <TabbedView>
    <Tab name="Creatures">
      <div>Creatures!</div>
    </Tab>
    <Tab name="Combat">
        <div>Combat!</div>
    </Tab>
    <NotTabButValidToo />
  </TabbedView>
);
你可以做的是声明一个道具,比方说tabs: TabProps[],传递创建这些Tabs所需的道具,而不是它们的 JSX,并将它们呈现在里面TabbedView:
interface TabbedViewProps {
  children?: never;
  tabs?: TabProps[];
}
...
const TabbedView: React.FC<TabbedViewProps > = ({ tabs }) => {
  return (
    ...
    { tabs.map(tab => <Tab key={ ... } { ...tab } />) }
    ...
  );
};
小智 5
我试图断言类型。你可以扔掉或者直接忽略。
interface TabbedViewProps {
  children?: React.ReactElement<ITabProps> | React.ReactElement<ITabProps>[]
}
在组件本身中映射子组件并断言或忽略
{React.Children.map(props.children, (tab) => {
  if(tab?.type != Tab) return;
  console.log(tab?.type == Tab);
  return tab;
})}
小智 -3
您在 Tab 渲染方法中返回的类型是 JSX.Element。这就是导致你的问题的原因。TabbedView 需要 Tab 类型的子级数组。我不确定您是否可以将某个组件指定为子类型。它可以是字符串或 JSX.Element。你能显示 Tab 的定义文件吗?
查看https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts查看 JSX.Element 界面的外观。
| 归档时间: | 
 | 
| 查看次数: | 12858 次 | 
| 最近记录: |