简体   繁体   English

我应该如何在 React 中使用 Typescript 声明无状态功能组件?

[英]How should I declare a Stateless Functional Component with Typescript in React?

I've seen two ways of declaring a SFC in React with Typescript, which are these two:我见过两种在 React with Typescript 中声明 SFC 的方法,它们是以下两种:

import * as React from 'react'

interface Props {
  message: string
}

const Component = (props: Props) => {
  const { message } = props
  return (
    <div>{message}</div>
  )
}

export default Component

Looks like React.SFC and React.StatelessComponent are deprecated. 看起来不推荐使用React.SFCReact.StatelessComponent

Use React.FunctionComponent instead: 改为使用React.FunctionComponent

import * as React from 'react'

interface IProps {
  text: string
}

export const MyComponent: React.FunctionComponent<IProps> = ({ text }: IProps): JSX.Element =>
<div>{text}</div>

Technically the name doesn't imply the same thing though, as Dan Abramov summed up nicely 从技术上讲,这个名字并不意味着同样的事情,正如Dan Abramov总结得很好

EDIT: Note it's often aliased as React.FC<> now. 编辑:注意它现在经常被别名为React.FC<>

The definition for React.StatelessComponent<T> is: React.StatelessComponent<T> 的定义是:

interface StatelessComponent<P> {
    (props: P & { children?: ReactNode }, context?: any): ReactElement<any>;
    propTypes?: ValidationMap<P>;
    contextTypes?: ValidationMap<any>;
    defaultProps?: Partial<P>;
    displayName?: string;
}

In your for snippet Component is inferred by the compiler to be: 在您的for for snippet中,编译器推断Component为:

(props: Props): ReactElement<any>

(or something similar). (或类似的东西)。

If you write the first one like this: 如果你写第一个这样的:

const Component = (props: Props & { children?: ReactNode }) => {
    ...
}

You are pretty much getting the same thing (as long as you don't use the properties of Component) 你几乎得到了同样的东西(只要你不使用Component的属性)

When you declare that const Component: React.StatelessComponent<Props> You basically declaring what this function gets, and what it returns: 当你声明const Component: React.StatelessComponent<Props>你基本上声明了这个函数得到了什么,以及它返回的内容:

interface StatelessComponent<P> { (props: P ... ): ReactElement<any>;

So for readability, I would actually do: 所以为了便于阅读,我实际上会:

const Component = (props: Props): JSX.Element => {

Because here the developer that looks into this code don't need to know what is the interface of StatelessComponent - he can just read what goes in and what goes out. 因为在这里查看此代码的开发人员不需要知道StatelessComponent的接口是什么 - 他只能读取进入的内容和出现的内容。

And basically, it is all a big: 基本上,它是一个很大的:

const Component: React.StatelessComponent<Props> = (props: IProps): JSX.Element =>

UPDATE: read the final part for React Hooks update 更新:阅读React Hooks更新的最后部分

The preferred one is React.SFC (Before React 16.7): 首选的是React.SFC(在React 16.7之前):

import * as React from 'react'

interface Props {
  message: string
}

const MyComponent: React.SFC<Props> = props => {
  const { message } = props
  return (
    <div>{message}</div>
  )
}

export default MyComponent

Why? 为什么?

SFC stands for Stateless Functional Component. SFC代表无状态功能组件。

About your 1st examle, given it was done "manually" it has some problems. 关于你的第一次考试,鉴于它是“手动”完成的,它有一些问题。 For example, it cannot point to props.children, because it wasn't defined in your interface. 例如,它不能指向props.children,因为它没有在您的界面中定义。 You don't have this problem with React.SFC. React.SFC没有这个问题。

(Note that Stateless Functional Component, Functional Component and Stateless Component seem to mean the same but actually are 3 different things ( Functional Components vs. Stateless Functional Components vs. Stateless Components ) (请注意,无状态功能组件,功能组件和无状态组件似乎意味着相同但实际上是3种不同的东西( 功能组件与无状态功能组件与无状态组件

Given you're looking for a Stateless Functional Component, React.SFC is exactly the way to go. 鉴于您正在寻找无状态功能组件,React.SFC正是您要走的路。 Other options may not be functional or may not be stateles, or may not fulfill a correct Component interface (like your manual example). 其他选项可能不起作用或可能不是状态,或者可能无法满足正确的Component接口(如手动示例)。

EDIT: Update since React Hooks arrived: 编辑:自React Hooks到达后更新:

Since React hooks arrived, function components can also have internal state, so the disctintion is smaller now. 由于React钩子到达,函数组件也可以具有内部状态,因此现在的分解更小。 The preferred way for function components (state or stateless) now is React.FunctionComponent 现在,函数组件(状态或无状态)的首选方法是React.FunctionComponent

const MyComponent: React.FunctionComponent<Props> = props => {
  // ... Same as above
}

Cheers, from La Paz, Bolivia. 干杯,来自玻利维亚拉巴斯。

At the time of this writing, the trend for writing Functional React Components are:在撰写本文时,编写功能性 React 组件的趋势是:

  • Do not use React.StatelessComponent , React.SFC (Both are deprecated)不要使用React.StatelessComponentReact.SFC (两者都已弃用)
  • Omit React.FunctionComponent and React.FC (For reasons outlined below)省略React.FunctionComponentReact.FC (原因如下)

So the recommended style could look like:所以推荐的样式可能如下所示:

import * as React from 'react'

interface Props {
  message: string
}

const Component = ({message}:Props) => {
  return (
    <div>{message}</div>
  )
}

export default Component

The reasoning for omitting React.FC and React.FunctionComponent can be traced to the removal from the CRA Typescript Template .省略React.FCReact.FunctionComponent的原因可以追溯到从 CRA Typescript Template 中删除

Additional thoughts can be found on Kent C Dodd's blog其他想法可以在Kent C Dodd 的博客上找到

In summary, the reason for removal of React.FC (and React.FunctionComponent ) is the usage provides little benefit and introduces possible problems.总而言之,删除React.FC (和React.FunctionComponent )的原因是使用带来的好处很少并且引入了可能的问题。 To quote Mr. Dodds:引用多兹先生的话:

[Omitting the usage] doesn't have any of the shortcomings of React.FC and it's no more complicated than typing the arguments to a regular function. [省略用法] 没有 React.FC 的任何缺点,它并不比将参数输入到常规函数中更复杂。

A very short summary of issues using React.FC使用React.FC的问题的简短总结

  1. Components accepts a children prop even if you don't use it即使您不使用组件,组件也接受children道具
  2. Generics are not supported不支持泛型
  3. Makes "component as namespace pattern" more awkward.使“组件作为命名空间模式”更加尴尬。
  4. Default Props do not work correctly默认道具无法正常工作
  5. It's as long, or longer than the alternative它与替代方案一样长或更长

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 TypeScript 中使用带有 React 无状态功能组件的子级 - How to use children with React Stateless Functional Component in TypeScript 如何在React无状态功能组件中测试道具? - How do I test props in a React stateless functional component? 如何从 React 功能组件声明 TypeScript 静态方法 - How To Declare TypeScript Static Method From React Functional Component 无状态功能组件 - React - Stateless Functional Component - React React - 如何确定组件是否无状态/功能? - React - how to determine if component is stateless/functional? 如何为 React 无状态功能组件模拟 api? - How to mock an api for a React stateless functional component? 如何在React Native的无状态功能组件中扩展Native组件的props TypeScript接口? - How to extend a native's component's props TypeScript interface in a stateless, functional component in React Native? 传递一个 React 函数式组件作为函数的参数时,我应该如何用 TS 声明函数参数类型 - When passing a React functional Component as a parameter of a function, how should I declare the function parameter type with TS 使用TypeScript创建一个接受数组的React无状态功能组件 - Using TypeScript To Create A React Stateless Functional Component That Accepts Array Typescript + React,从无状态功能组件渲染数组 - Typescript + React, rendering an array from a stateless functional component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM