为子元素提供属性时,如何为 React.cloneElement 分配正确的类型?

2024-05-24

我正在使用 React 和 Typescript。我有一个充当包装器的反应组件,我希望将其属性复制到其子组件。我正在遵循 React 的使用克隆元素的指南:https://facebook.github.io/react/blog/2015/03/03/react-v0.13-rc2.html#react.cloneelement https://facebook.github.io/react/blog/2015/03/03/react-v0.13-rc2.html#react.cloneelement。但使用时使用React.cloneElement我从 Typescript 收到以下错误:

Argument of type 'ReactChild' is not assignable to parameter of type 'ReactElement<any>'.at line 27 col 39
  Type 'string' is not assignable to type 'ReactElement<any>'.

如何为react.cloneElement分配正确的类型?

这是一个重复上述错误的示例:

import * as React from 'react';

interface AnimationProperties {
    width: number;
    height: number;
}

/**
 * the svg html element which serves as a wrapper for the entire animation
 */
export class Animation extends React.Component<AnimationProperties, undefined>{

    /**
     * render all children with properties from parent
     *
     * @return {React.ReactNode} react children
     */
    renderChildren(): React.ReactNode {
        return React.Children.map(this.props.children, (child) => {
            return React.cloneElement(child, { // <-- line that is causing error
                width: this.props.width,
                height: this.props.height
            });
        });
    }

    /**
     * render method for react component
     */
    render() {
        return React.createElement('svg', {
            width: this.props.width,
            height: this.props.height
        }, this.renderChildren());
    }
}

问题是的定义ReactChild https://github.com/DefinitelyTyped/DefinitelyTyped/blob/949922e0959ccea0cad7a6fa787b63b7d4e67d3f/types/react/index.d.ts#L196这是:

type ReactText = string | number;
type ReactChild = ReactElement<any> | ReactText;

如果你确定child总是一个ReactElement然后投射它:

return React.cloneElement(child as React.ReactElement<any>, {
    width: this.props.width,
    height: this.props.height
});

否则使用isValidElement 类型保护 https://github.com/DefinitelyTyped/DefinitelyTyped/blob/949922e0959ccea0cad7a6fa787b63b7d4e67d3f/types/react/index.d.ts#L351:

if (React.isValidElement(child)) {
    return React.cloneElement(child, {
        width: this.props.width,
        height: this.props.height
    });
}

(我以前没有使用过它,但根据定义文件它就在那里)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为子元素提供属性时,如何为 React.cloneElement 分配正确的类型? 的相关文章

随机推荐

  • 如何在输入时格式化 contenteditable div?

    我正在尝试编写一个函数 允许 contenteditable div 在用户输入 div 时执行一些自动格式化 到目前为止我只能让它在 IE 中运行 有人可以帮助我吗 function formatOnKeyUp if window get
  • 通过 Ajax 加载内容

    好的 我对 ajax 和从外部加载内容还很陌生 如果您能深入了解我的问题 我将不胜感激 我目前有一个空的隐藏 div 单击链接后应在其中加载 ajax 内容 div div 我目前有一个链接列表 它们都具有相同的类 我希望在单击时 空白 d
  • Windows 更新后 Active 设置为 False 时 TIdHttpServer 冻结

    我们有一个 Indy 版本 10 6 1 5235 TIdHttpServer 服务 多年来一直与 Delphi 2007 配合良好 在最新的 Windows 更新 KB4338815 和 KB4338830 之后 我们注意到当 TIdHt
  • uWSGI 皇帝权限被拒绝,除非 root

    我尝试使用二进制文件本身的标志 uid www data gid www data 并将其设置在我的配置中 uid www data gid www data 但套接字总是由我正在使用的帐户生成 因此我从 nginx 收到权限被拒绝的错误
  • PHP Session Id 在页面之间发生变化

    我有一个问题 我在 2 个页面之间丢失了 PHP 会话 session start 包含在一个名为 session inc php 的文件中 该文件包含在每个需要设置会话的页面中 这适用于网站上除一个特定页面 member profile
  • Pandas DataFrame 自定义 agg 函数奇怪的行为

    我想使用自定义函数沿轴聚合 Pandas DataFrame 但我无法弄清楚该函数应返回什么 df pd DataFrame np arange 50 reshape 10 5 您可以将 numpy 函数传递给DataFrame agg C
  • 使用 Hibernate 防止无限循环数据检索

    我想知道 想象一个场景 例如 POJO public class User private String userName private String name private String surname private List
  • JavaScript 开关(真)

    你好 我正在尝试处理 ajax json 响应 这是我的代码 success function j switch true case j choice1 alert choice2 break case j choice2 alert ch
  • 如何在 LLVM 中实现字符串数据类型?

    我一直在看LLVM http llvm org 最近 我发现它是一个非常有趣的架构 然而 浏览教程和参考材料 我看不到任何关于如何实现的示例string http en wikipedia org wiki String computer
  • 如何将上下文从一个活动传递到另一个活动?

    我有一个主要活动 它调用另一个活动来显示一些数据 我有一个私有数据库帮助程序对象 我在整个主要活动代码中使用它 有没有办法以优雅的方式将我的主要活动的上下文传递给我的子活动 即 来自子类 类似getCallingActivityContex
  • 如何让 DataTemplate.DataTrigger 检查大于或小于?

    下列DataTemplate DataTrigger如果是 则使年龄显示为红色equal to 30 如果是的话 如何使年龄显示为红色比 更棒 30
  • 如何在 C 中创建最低有效位设置为 1 的掩码

    这个功能如何运作 最低有效 n 位设置为 1 的掩码 Example n 6 gt 0x2F n 17 gt 0x1FFFF 我根本不明白这些 尤其是 n 6 gt 0x2F 另外 什么是面膜 通常的方法是采取1 并将其左移n位 这会给你类
  • 使用 CodeDOM 将程序集添加到 BuildManager 会导致间歇性错误

    我正在使用 CodeDOM 在运行时创建内存中程序集 如下所示 public Assembly Compile CodeCompileUnit targetUnit string path Path GetDirectoryName new
  • cUrl 在本地主机上工作正常,但在服务器上不起作用,仅显示空白页面

    当我在服务器上运行以下代码时 它只显示空白页面并突然停止进一步执行 我还检查了已安装的服务器上的 cUrl 这是我的代码 ftp server ftps server Voorraadtonen link csv ch curl init
  • 表单帖子上的 asp.net mvc 编码

    我在我的 asp net mvc 表单 带有文本区域的 nicedit 中使用富文本编辑器 当我在帖子上提交表单时 因为它不是 html 编码的 我收到以下消息 从客户端检测到潜在危险的 Request Form 值 如何对 post 上的
  • 将自定义属性添加到 Tk 小部件

    我的主要目标是向小部件添加隐藏标签或字符串之类的内容 以在其上保存简短信息 我想到创建一个新的自定义 Button 类 在本例中我需要按钮 它继承所有旧选项 这是代码 form tkinter import class NButton Bu
  • 在windows + opengl中选择图形设备

    我知道如何使用 openGL 打开窗口 使用 Win32 或其他工具包 但是当系统有2块显卡时 如何选择要渲染的图形设备 我的编程语言是 C 我专注于 Windows 但任何示例都将受到欢迎 编辑 也许更好地解释我的问题是个好主意 以便添加
  • 实体框架代码首次日期字段创建

    我正在使用实体框架代码优先方法来创建我的数据库表 下面的代码 创建一个DATETIME数据库中的列 但我想创建一个DATE柱子 DataType DataType Date DisplayFormatAttribute ApplyForma
  • 将一个 IEnumerable 拆分为多个 IEnumerable

    我是 linq 新手 我需要根据指示器将 Couple string text bool Indicator 类型的 IEnumerable 拆分为多个 IEnumerable 我尝试使用skipWhile 和 TakeWhile 但没有找
  • 为子元素提供属性时,如何为 React.cloneElement 分配正确的类型?

    我正在使用 React 和 Typescript 我有一个充当包装器的反应组件 我希望将其属性复制到其子组件 我正在遵循 React 的使用克隆元素的指南 https facebook github io react blog 2015 0