React无状态组件的TypeScript返回类型是什么?

ahs*_*tro 10 typescript reactjs

这里的返回类型是什么?

const Foo
  : () => // ???
  = () => (
    <div>
      Foobar
    </div>
  )
Run Code Online (Sandbox Code Playgroud)

ahs*_*tro 10

正确的返回类型是ReactElement<P>,但是更好的选择是React.StatelessComponent<P>像这样使用

const Foo
  : React.StatelessComponent<{}>
  = () => (
    <div>
      Foobar
    </div>
  )
Run Code Online (Sandbox Code Playgroud)

  • 这已经过时了 (3认同)
  • React.StatelessComponent已被弃用,这意味着React.FC是组件的正确类型。该函数将返回一个ReactElement。从最新的React版本开始,功能组件不再被视为“无状态”。请改为使用FunctionComponent。 (2认同)

Aaa*_*ron 10

不建议使用此答案中提到的StatelessComponent类型,因为在引入了Hooks API之后,它们并不总是无状态的。

一个功能组件是类型React.FunctionComponent,它具有一个别名,React.FC可以使事情保持简洁。

它具有一个必填属性,即一个函数,该函数将返回ReactElementnull。它有几个可选的属性,如propTypescontextTypesdefaultPropsdisplayName

这是一个例子:

const MyFunctionComponent: React.FC = (): ReactElement => {
  return <div>Hello, I am a function component</div>
}
Run Code Online (Sandbox Code Playgroud)

以下是@ types / react 16.8.24中的类型:

type FC<P = {}> = FunctionComponent<P>;

interface FunctionComponent<P = {}> {
    (props: PropsWithChildren<P>, context?: any): ReactElement | null;
    propTypes?: WeakValidationMap<P>;
    contextTypes?: ValidationMap<any>;
    defaultProps?: Partial<P>;
    displayName?: string;
}
Run Code Online (Sandbox Code Playgroud)


Vis*_*ria 10

interface ISomeCoolInterface {
   some: 'string';
   cool: 'string';
   props: 'string' 
}    

const SomeCoolComponent
    : React.FC<ISomeCoolInterface> 
    = ({ some, cool, props }): JSX.Element => {
        return <SomeCoolComponent>{some, cool, props}</SomeCoolComponent>      
    }
Run Code Online (Sandbox Code Playgroud)

这里重要的一点是返回类型 JSX.Element

  • 是的,“ReactElement”是较新支持的返回类型。当我转向“eslint”时,我看到了这个变化 (2认同)

Luk*_*ams 7

如果使用function关键字,最佳返回类型似乎是JSX.Element | null.

目前,我们的团队使用 JSXNode 作为简写,因为这是唯一可以作为 JSX 结果直接返回的两种类型:

type JSXNode = JSX.Element | null;

编辑:看起来最终 React.ReactNode 是 JSX 的预期返回类型,但目前不可能。(参考


背景:

这里的答案似乎都没有解决最常见的现代情况 - 您有一个返回元素的函数。该返回什么类型?

function MyComponent(): SomeTypeHere {
  return <>...</>;
}
Run Code Online (Sandbox Code Playgroud)

隐藏组件的推荐方法是返回 null,因此不清楚什么是干净的返回类型。输入 JSX.Element | null 到处都是,甚至制作这样的自定义类型似乎应该是没有必要的,因为这种情况是多么普遍。ReactNode 也不起作用,因为 undefined 不能作为 JSX 返回。

总的来说,最好的返回类型似乎是JSX.Element | null. FC这是在不使用关键字时使用的类型的返回类型function

const MyComponent: FC = () => { <>...</> }
Run Code Online (Sandbox Code Playgroud)