【发布时间】:2017-10-23 07:47:30
【问题描述】:
这里的返回类型是什么?
const Foo
: () => // ???
= () => (
<div>
Foobar
</div>
)
【问题讨论】:
标签: reactjs typescript
这里的返回类型是什么?
const Foo
: () => // ???
= () => (
<div>
Foobar
</div>
)
【问题讨论】:
标签: reactjs typescript
this answer 中提到的StatelessComponent 类型已被弃用,因为在引入 Hook API 后,它们并不总是无状态的。
函数组件的类型为 React.FunctionComponent,它有一个别名 React.FC 以保持简洁明了。
它有一个必需的属性,一个函数,它将返回ReactElement 或null。它有一些可选属性,例如propTypes、contextTypes、defaultProps 和displayName。
这是一个例子:
const MyFunctionComponent: React.FC = (): ReactElement => {
return <div>Hello, I am a function component</div>
}
这里是来自@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;
}
【讨论】:
interface ISomeCoolInterface {
some: 'string';
cool: 'string';
props: 'string'
}
const SomeCoolComponent
: React.FC<ISomeCoolInterface>
= ({ some, cool, props }): JSX.Element => {
return <SomeCoolComponent>{some, cool, props}</SomeCoolComponent>
}
这里的重要一点是返回类型JSX.Element
【讨论】:
ReactElement 是较新的受支持的返回类型。我在搬到eslint时看到了这个变化
这里正确的返回类型是ReactElement<P>,但更好的选择是像这样使用React.StatelessComponent<P>
const Foo
: React.StatelessComponent<{}>
= () => (
<div>
Foobar
</div>
)
【讨论】:
as of recent React versions, function components can no longer be considered 'stateless'. Please use FunctionComponent instead.
如果使用function 关键字,最佳返回类型似乎是JSX.Element | null。
目前我们的团队使用 JSXNode 作为简写,因为只有这两种类型可以直接作为 JSX 结果返回:
type JSXNode = JSX.Element | null;
编辑:看起来 React.ReactNode 最终是 JSX 的预期返回类型,但目前不可能。 (Reference)
这里的答案似乎都没有解决最常见的现代情况 - 您有一个返回元素的函数。这应该返回什么类型?
function MyComponent(): SomeTypeHere {
return <>...</>;
}
隐藏组件的推荐方法是return null,所以不清楚它会是什么干净的返回类型。键入 JSX.Element |考虑到这种情况的普遍性,null 无处不在,甚至制作这样的自定义类型似乎是不必要的。 ReactNode 也不起作用,因为 undefined 不能作为 JSX 返回。
总体上最好的返回类型似乎是JSX.Element | null。这是 FC 类型的返回类型,如果您不使用 function 关键字,则使用该类型:
const MyComponent: FC = () => { <>...</> }
【讨论】:
我还要添加.SFC,它代表无状态功能组件。
const Foo
: React.SFC<{}>
= () => (
<div>
Foobar
</div>
)
【讨论】:
见https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts
每个 JSX 元素只是调用 React.createElement(component, props, ...children) 的语法糖。
function createElement<P extends DOMAttributes<T>, T extends Element>(
type: string,
props?: ClassAttributes<T> & P,
...children: ReactNode[]): DOMElement<P, T>;
所以是DOMElement<P, T>
【讨论】:
*Elements。 github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/…
DOMElement<any, any> 会抛出错误,而ReactElement<any> 很好。