我应该如何在 React 中使用 Typescript 声明无状态功能组件? [英] How should I declare a Stateless Functional Component with Typescript in React?

查看:40
本文介绍了我应该如何在 React 中使用 Typescript 声明无状态功能组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过两种在 React 中使用 Typescript 声明 SFC 的方法,就是这两种:

I've seen two ways of declaring a SFC in React with Typescript, which are these two:

import * as React from 'react'

interface Props {
  message: string
}

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

export default Component

和:

import * as React from 'react'

interface Props {
  message: string
}

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

export default Component

来自这个问题我看到,如果您在组件中使用它,则可以通过第二种方式从界面中省略子项.

From this question I see that with the second way you can omit children from your interface if you are using it in your component.

还有什么不同吗?哪一个是首选?为什么?

Are there any more differences? Which one is the preferred one and why?

推荐答案

看起来 React.SFCReact.StatelessComponent 已被弃用.

Looks like React.SFC and React.StatelessComponent are deprecated.

使用 React.FunctionComponent 代替:

import * as React from 'react'

interface IProps {
  text: string
}

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

从技术上讲,这个名字并不意味着同样的事情,因为 Dan Abramov 总结得很好

Technically the name doesn't imply the same thing though, as Dan Abramov summed up nicely

请注意,现在通常将其别名为 React.FC<>.

Note it's often aliased as React.FC<> now.

这篇关于我应该如何在 React 中使用 Typescript 声明无状态功能组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆