向子项提供属性时,如何为 React.cloneElement 分配正确的类型? [英] How to assign the correct typing to React.cloneElement when giving properties to children?

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

问题描述

我正在使用 React 和 Typescript.我有一个充当包装器的反应组件,我希望将其属性复制到其子项.我正在遵循 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
});

否则使用一个>:

Otherwise use the isValidElement type guard:

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 分配正确的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆