【问题标题】:How to type property 'key' on Preact stateless component如何在 Preact 无状态组件上键入属性“键”
【发布时间】:2019-10-08 11:06:38
【问题描述】:

这里是无状态组件:

interface Props {
  children: JSX.Element;
  title: string;
  isHidden: boolean;
}

function TabContent({ children, title, isHidden }: Props): JSX.Element {
  return (
    <section
      id={title}
      hidden={isHidden}
    >
      {children}
    </section>
  );
}

export default TabContent;

我在map 中使用它,如下所示:

createTabContent = tabs => {
    return tabs.map((tab, id) => (
      <TabContent key={id} title={tab.title} isHidden={!(this.state.activeTab === id)}>
        {tab}
      </TabContent>
    ));
  };

但 Typescript 抱怨 Property 'key' does not exist on type Props

我研究了如何在 React 中键入无状态组件,例如 guide。它们都需要访问 React 模块,但我使用的是 Preact..

【问题讨论】:

  • 我想你可以将key?: string | number(或任何有意义的类型)添加到Props
  • 您是否尝试过使用 preact 本身的 FunctionComponentComponentTypegithub.com/developit/preact/blob/master/src/index.d.ts#L65
  • 类似const TabContent: FunctionComponent&lt;Props&gt; = ({ children, title, isHidden }) =&gt; ...
  • 我像这样导入import { h, FunctionalComponent } from "preact";。有用。谢谢!
  • 我会发布作为答案然后

标签: reactjs typescript preact


【解决方案1】:

Preact 具有类似于 React 的组件 typings。所以你可以使用ComponentTypeFunctionComponentFunctionalComponent之一:

import { FunctionalComponent } from 'preact';

const TabContent: FunctionalComponent<Props> = ({ children, title, isHidden }) => (
    <section
        id={title}
        hidden={isHidden}
    >
        {children}
    </section>
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-07
    • 1970-01-01
    • 2022-10-31
    • 2020-02-22
    • 2023-03-26
    • 2011-08-11
    • 2019-07-05
    • 2020-03-28
    相关资源
    最近更新 更多