【发布时间】:2021-06-13 12:58:28
【问题描述】:
当使用命名函数而不是箭头函数时,在用 typescript 编写的 React 组件中使用 children 关键字传递子节点的正确方法是什么?
在箭头函数中我可以这样写:
const MyComponent: React.FC = ({children}) => {
return <div>{children}</div>
}
export default MyComponent;
但是我如何用normal 函数做同样的事情呢?我试过了
import React from "react";
function MyComponent({children}): JSX.Element{
return <div>{children}</div>
}
export default MyComponent;
但是eslint抛出如下错误:
var children: any
Object pattern argument should be typed. eslint(@typescript-eslint/explicit-module-boundary-types)
'children' is missing in props validation eslint(react/prop-types)
我可以通过从 React 导出 ReactNode 来消除错误。
import React, { ReactNode } from "react"
function MyComponent({children}: ReactNode): JSX.Element{
return <div>{children}</div>
}
export default MyComponent;
但这被认为是一种可行的方法,还是有其他被认为是最佳实践的方法?
【问题讨论】:
-
最佳实践是箭头函数
-
是吗?到目前为止,我一直在使用箭头函数,但是在看到 next.js 从他们的示例中省略它们以及仅使用命名函数的反应文档之后,我开始怀疑它们是否是最佳实践。很想对这个话题有所了解。这是来自 next.js 示例存储库的示例:github.com/vercel/next.js/tree/canary/examples/blog-starter/…
-
有一个类型
PropsWithChildren<P>可以从 React 导入。这与在 props 中添加{children?: ReactNode}相同,但可能更具可读性。 -
@LindaPaiste 谢谢!不知道这个。
标签: javascript reactjs typescript react-functional-component