提问者:小点点

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


我见过两种在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

和:

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

从这个问题中,我看到了第二种方法,如果您在组件中使用子接口,您可以从接口中省略子接口。

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


共3个答案

匿名用户

看起来像React。SFCReact。不建议使用StatelessComponent

使用React。功能组件

import * as React from 'react'

interface IProps {
  text: string
}

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

从技术上讲,这个名字并不意味着同样的事情,丹·阿布拉莫夫很好地总结了这一点

编辑:注意,它通常被别名为React。常设费用

匿名用户

React的定义。无状态组件

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

在for代码段中,编译器推断组件为:

(props: Props): ReactElement<any>

(或类似的东西)。

如果你像这样写第一个:

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

你几乎得到了同样的东西(只要你不使用组件的属性)

匿名用户

当您声明const Component: React时。无状态组件

接口组件

为了便于阅读,我实际上会:

const组件=(props:props):JSX。元素=

因为在这里,研究此代码的开发人员不需要知道无状态组件的接口是什么——他只需要读取输入和输出的内容。

基本上,这都是一个大问题:

const组件:React。无状态组件