【问题标题】:React children with typescript用打字稿反应孩子
【发布时间】:2021-11-18 01:36:06
【问题描述】:

我无法为 react 子级设置正确的类型。

export const recursiveCloneChildren = (
  children: React.ReactNode,
  handleChildChange,
  disableContent: boolean,
) => {
  return React.Children.map(children, (child) => {
    if (!isObject(child)) {
      return child;
    }

    let childProps = {
      ...child.props,
      disabled: child.props.disabled || disableContent,
    };

    const requiredOrValidatableChildProps = {
      ...childProps,
      checkValidationState: handleChildChange,
    };

    if (child.props.required || child.props.validatable) {
      childProps = {
        ...requiredOrValidatableChildProps,
      };
    }

    if (child.props.children) {
      childProps.children = recursiveCloneChildren(child.props.children, handleChildChange, disableContent);
    }

    return React.cloneElement(child, childProps);
  });
};

我收到了这个错误

类型“{}”上不存在属性“props”| ReactElement |反应节点数组 | ReactPortal'。
类型“{}”上不存在属性“props”。

我尝试直接为孩子设置类型( React.ReactChild ),并在孩子身上显示另一个错误。 怎么解决?

【问题讨论】:

  • 什么是`React.Children.map`?你是说children.map(child => {return something..])
  • 通常你只需要让孩子通过被渲染为{children},它被输入为React.ReactNode。这个组件非常不习惯。这个组件有什么作用?它是如何使用的?
  • @AlexWayne 它不是一个组件,它是一个辅助函数。
  • 我在 Form 组件中递归克隆子组件,该组件将处理表单验证和子验证。

标签: javascript reactjs typescript


【解决方案1】:

我不太喜欢你尝试做的事情,因为如果我在代码库中找到它,我会很困惑。

但是要回答你的问题。传递给Children.map 的函数中的child 参数是ReactNode 类型。这是最通用的类​​型,这意味着您最终可以得到几乎任何可以成为有效孩子的东西。我实际上不知道您的代码是否可以工作,但考虑到您想要访问道具,我假设您想要确保您在 ReactElement 上运行。在这种情况下,您的isObject 检查不够详尽。你需要的是类型保护。

所以快速而肮脏的选择是编写自己的类型保护,这样实际上就足够了:

function isReactElement(child: React.ReactNode): child is React.ReactElement {
  return isObject(child) && 'props' in child;
}

然后代替

if (!isObject(child)) {
  return child;
}

你只是这样做

if (!isReactElement(child)) {
  return child;
}

它有效。然而,一个更好的主意可能是使用react-is 库,它是一个官方的、由 Facebook 维护的库,它在许多 React 库中被广泛使用,它基本上完全符合您的要求,但检查比我上面建议的要好得多。在你的情况下,你想使用isElement,就像我上面展示的那样。只需确保也安装@types/react-is

【讨论】:

    猜你喜欢
    • 2023-04-06
    • 1970-01-01
    • 2020-10-24
    • 2019-07-11
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    相关资源
    最近更新 更多