reactjs - 为子项提供属性时如何将正确的类型分配给 React.cloneElement?

标签 reactjs typescript ecmascript-6

我正在使用 React 和 Typescript。我有一个充当包装器的 react 组件,我希望将它的属性复制到它的子组件。我正在遵循 React 的克隆元素使用指南: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;

如果您确定 child 始终是 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
    });
}

(我没用过,但是根据定义文件是有的)

关于reactjs - 为子项提供属性时如何将正确的类型分配给 React.cloneElement?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42261783/

相关文章:

reactjs - 使用 React Router 保留侧边栏

javascript - 可以从 Angular 4 组件模板属性调用函数吗?

typescript - 如何在 TypeScript 中指定类型化对象文字?

html - 根据条件禁用输入

javascript - 不可点击可触摸可突出显示

javascript - 如何使用 es6 (reactjs) 通过索引在项目列表中查找对象

javascript - 组合插入数组Reduce中的项目

javascript - react 。尝试从 onClick 事件调用自定义 Hook

javascript - ReactJS表单组件的最佳实践

javascript - 根据完整日历日 View 中的数据显示时段