将子节点传递给功能性反应组件编写的打字稿

时间:2021-03-16 08:55:42

标签: javascript reactjs typescript react-functional-component

当使用命名函数而不是箭头函数时,在用 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;

但这是否被认为是一种可行的方法,或者是否还有其他被认为是最佳实践的方法?

2 个答案:

答案 0 :(得分:3)

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

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

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

答案 1 :(得分:0)

你应该创建一个道具界面。

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