reactjs – 如何在为子项提供属性时为React.cloneElement指定正确的类型?

我正在使用React和Typescript.我有一个反应组件作为包装器,我希望将其属性复制到其子代.我正在遵循React的使用clone元素的指南: 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());
    }
}
问题是 definition for ReactChild是这样的:
type ReactText = string | number;
type ReactChild = ReactElement<any> | ReactText;

如果您确定该子项始终是ReactElement,则将其强制转换为:

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

否则使用isValidElement type guard

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

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

相关文章

一、前言 在组件方面react和Vue一样的,核心思想玩的就是组件...
前言: 前段时间学习完react后,刚好就接到公司一个react项目...
前言: 最近收到组长通知我们项目组后面新开的项目准备统一技...
react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...