【问题标题】:Typescript Stateless React Component as named functionTypescript Stateless React 组件作为命名函数
【发布时间】:2020-07-28 15:37:12
【问题描述】:

假设我有一个名为 Link 的 React 组件:

function Link(props) {
  return <a href={props.url}>{props.children}</a>
}

如何键入这个函数而不把它变成箭头函数?

这似乎不起作用:

interface ILink {
  url: string
}

function Link(props: React.FC<ILink>) { }

// Property 'url' does not exist on type 'FC<ILink>'.
// Property 'children' does not exist on type 'FC<ILink>'.

但作为箭头功能,它会立即起作用吗?

interface ILink {
  url: string
}

const Link: React.FC<ILink> = (props) => { }

// Compiles

【问题讨论】:

    标签: reactjs typescript typescript-generics react-typescript


    【解决方案1】:

    你必须使用组合 React.PropsWithChildrenReact.ReactElement 所以它变成:

    function Link(props: PropsWithChildren<ILink>): ReactElement {}
    

    【讨论】:

      猜你喜欢
      • 2019-11-09
      • 2018-05-28
      • 2020-09-29
      • 2018-08-18
      • 2018-05-06
      • 1970-01-01
      • 2020-11-07
      • 2020-03-12
      • 2016-06-26
      相关资源
      最近更新 更多