本文介绍了给子级属性时,如何为React.cloneElement分配正确的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using React and Typescript. I have a react component that acts as a wrapper, and I wish to copy its properties to its children. I am following React's guide to using clone element: https://facebook.github.io/react/blog/2015/03/03/react-v0.13-rc2.html#react.cloneelement. But when using using React.cloneElement I get the following error from 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分配正确的类型?

这是一个复制上面错误的示例:

Here is an example that replicates the error above:

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 的定义是这样的:

The problem is that the definition for ReactChild is this:

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

如果您确定child始终是ReactElement,则将其强制转换:

If you're sure that child is always a ReactElement then cast it:

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

否则,请使用 isValidElement类型防护 a>:

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

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

(I haven't used it before, but according to the definition file it's there)

这篇关于给子级属性时,如何为React.cloneElement分配正确的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!