【问题标题】:children.toArray() - TS2339: Property 'key' does not exist on type 'ReactChild | ReactFragment | ReactPortal'... - React Typescriptchildren.toArray() - TS2339:“ReactChild | 类型”上不存在属性“键”反应片段 | ReactPortal'... - 反应打字稿
【发布时间】:2022-07-30 00:50:31
【问题描述】:

我正在创建一个 TypeScript 组件/包装器,它在每个孩子之间添加一个分隔符:

import React, { FC, Children } from 'react'

const DividedChildren: FC = ({ children }) => {
  return (
    <div>
      {Children.toArray(children).map((node, index) => {
        if (index === 0) return node
        return (
          <Fragment key={node.key}> // TS Error, but code works fine
            <div className="divider" />
            {node}
          </Fragment>
        )
      })}
    </div>
  )

但是,当我尝试将孩子的 key 移动到他的新容器中时遇到 TypeScript 错误:
TS2339: Property 'key' does not exist on type 'ReactChild | ReactFragment | ReactPortal'.   Property 'key' does not exist on type 'string'.

如何以类型安全的方式将每个项目的键移动到其新容器中?

【问题讨论】:

  • 在访问子属性时遇到了同样的问题。类型“ReactChild”上不存在属性“props”。

标签: reactjs typescript key children


【解决方案1】:

我已经设法通过将 node 转换为 ReactElement 类型来解决这个特定错误。

Children.toArray(children).map((node: React.ReactElement, index) => { //...

【讨论】:

    猜你喜欢
    • 2020-12-18
    • 2020-11-10
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 2022-11-04
    • 2019-05-05
    • 2021-01-07
    • 2018-12-11
    相关资源
    最近更新 更多