【问题标题】:React TypeScript - children of HTML and React ComponentsReact TypeScript - HTML 和 React 组件的子代
【发布时间】:2021-07-03 19:39:12
【问题描述】:

我有一个PopoverMenu 组件,我想在其中访问和使用children 属性。我看过很多与此类似的帖子,但不足以帮助我解决问题。

children 可以是标准 HTML 或其他 React 组件。

这里是PopoverMenu 组件:

export const PopoverMenu = (children) =>
{
    const [visible, setVisible] = useState(true);

    if (visible) {
        return (
            <ul ref={ node } className="popover-menu">
                { children }
            </ul>
        )
    }
}

...这是正在使用的组件...

<PopoverMenu>
    <PopoverMenuItem>
      Edit
    </PopoverMenuItem>
    <PopoverMenuItem>
      Delete
    </PopoverMenuItem>
</PopoverMenu>

...或者...

<PopoverMenu>
    <li>
      <a>Edit</a>
    </li>
    <li>
      <a>Delete</a>
    </li>
</PopoverMenu>

我已经为children 尝试了多种类型,但我的 IDE 似乎对所有这些类型都有抱怨。其中包括:

ReactNode

HTMLElement

ReactChildren

什么类型可以给我想要的结果,为什么?

【问题讨论】:

    标签: reactjs typescript tsx


    【解决方案1】:

    孩子的类型应该是ReactNode

    但你需要更正道具解构:它应该是({ children })

    另外,您需要从 else 块中返回一些内容。如果你不想显示任何内容,你可以return null

    【讨论】:

    • 所以在将我的代码更新到这个({children}: {children: ReactNode}) 之后,当我尝试使用该组件时,我会从我的IDE 'PopoverMenu' cannot be used as a JSX component. Its return type 'Element | undefined' is not a valid JSX element.得到这个
    • github.com/typescript-cheatsheets/react 似乎是一个很好的 React Typings 集合。
    猜你喜欢
    • 2023-01-24
    • 2020-06-03
    • 1970-01-01
    • 1970-01-01
    • 2022-11-26
    • 1970-01-01
    • 1970-01-01
    • 2020-06-10
    • 2019-05-10
    相关资源
    最近更新 更多