【问题标题】:Passing child nodes to a functional react component written typescript将子节点传递给功能性反应组件编写的打字稿
【发布时间】: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&lt;P&gt; 可以从 React 导入。这与在 props 中添加 {children?: ReactNode} 相同,但可能更具可读性。
  • @LindaPaiste 谢谢!不知道这个。

标签: javascript reactjs typescript react-functional-component


【解决方案1】:

你应该创建一个道具接口。

interface MyComponentProps {
   children: React.ReactNode
}
function MyComponent({ children }: MyComponentProps ): JSX.Element {
  return <div>{children}</div>;
}

【讨论】:

    【解决方案2】:

    你需要给孩子参数正确的类型..

    这样的事情应该可以工作..

    function MyComponent({ children }: {children: React.ReactNode}): JSX.Element {
      return <div>{children}</div>;
    }
    

    【讨论】:

    • 这是正确的,但请注意这使得children 成为必需。有时这是期望的行为,但更常见的是让它成为一个可选的道具(因为它在 React.FC 类型中),即 {children?: React.ReactNode}
    猜你喜欢
    • 2021-02-28
    • 2021-11-13
    • 2021-11-20
    • 2022-12-07
    • 2022-10-06
    • 2021-11-10
    • 2021-11-06
    • 2019-01-02
    • 1970-01-01
    相关资源
    最近更新 更多