【问题标题】:When passing a React functional Component as a parameter of a function, how should I declare the function parameter type with TS将React函数式组件作为函数的参数传递时,我应该如何用TS声明函数参数类型
【发布时间】:2021-12-16 18:13:04
【问题描述】:

我对函数参数的类型声明有疑问。请看下面的代码,

const FunctionalComponent = ({propA,propB}: FunctionalComponentProps): JSX.Element => {
   return 
}

现在我想将 FunctionalComponent 作为参数传递给另一个函数。我应该如何声明参数类型?

const Foo = (
   para1: string,
   TheFunctionalComponent: ??? // Tried React.FC<any>, it work, want to provide more strict such as React.FC<FunctionalComponentProps>, this way it does not work. Is the React.FC<any> the only way? 
)

【问题讨论】:

标签: reactjs typescript react-functional-component


【解决方案1】:

考虑这个例子:

import React, { FC } from 'react'

export interface ChildComponentProps {
  name: string;
  id: string;
}

export const ChildComponent = ({ name, id }: ChildComponentProps): JSX.Element => (
  <div>
    Hi {name} my id is {id}
  </div>
);


const ParentComponent: FC<{ Comp: FC<ChildComponentProps> }> = ({ Comp }) =>
  <Comp name={"2"} id={"3"} />

const App = <ParentComponent Comp={ChildComponent} />

Playground

您还应该提供ParentComponent的类型

更新

import React, { FC } from 'react'

export interface ChildComponentProps {
  name: string;
  id: string;
}

export const ChildComponent = ({ name, id }: ChildComponentProps): JSX.Element => (
  <div>
    Hi {name} my id is {id}
  </div>
);


const ParentComponent = (Comp: FC<ChildComponentProps>) =>
  <Comp name={"2"} id={"3"} />

const App = ParentComponent(ChildComponent)

Playground

更通用的方法:

import React, { FC } from 'react'

export interface ChildComponentProps {
  name: string;
  id: string;
}

export const ChildComponent = ({ name, id }: ChildComponentProps): JSX.Element => (
  <div>
    Hi {name} my id is {id}
  </div>
);


const ParentComponent = <Props,>(Comp: FC<Props>) =>
  (props: Props) => <Comp {...props} />

const App = ParentComponent(ChildComponent)({ name: 'John', id: '#1' })

Playground

【讨论】:

  • 谢谢你的朋友,它看起来是正确的答案,但有点不同。接受组件的函数是函数,而不是函数组件。所以我们不能使用像 {Comp} 这样的 props 形式,我认为这就是问题所在
  • @EvenZhi 我不明白。您能否提供更多背景信息?
  • Parent Function 的用例是 const a = ParentFunction(a,b,WithComponent)。它不像组件那样将参数传递给 props 对象,因此我们不能声明一个 WithComponent 类型,然后像 ({Comp}:WithComponent) 一样声明 ParentComponent。我不确定你是否理解
  • 通常我们使用像 这样的组件。那将有一个道具对象。然而,这一次不同。我必须以这种方式使用 FunctionalComponent:const a = FunctionalComponent(propa)。因此,FunctionalComponent 的 prop 类型声明方式会有所不同。
  • 能否提供一个预期意外错误的示例?我有点困惑
猜你喜欢
  • 1970-01-01
  • 2021-04-13
  • 2020-10-11
  • 1970-01-01
  • 2020-03-22
  • 2019-02-26
  • 2021-04-24
  • 2012-05-06
  • 2016-12-30
相关资源
最近更新 更多