在给子元素赋予属性时,如何为 React.cloneElement 赋予正确的类型?

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

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());
}
}
56253 次浏览

The problem is that the definition for ReactChild is this:

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

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)

This solved it for me:

React.Children.map<ReactNode, ReactNode>(children, child => {
if(React.isValidElement(child)) {
return React.cloneElement(child, props
)
}
}

quite simplle solution

 import React, { Children } from "react";




const child = Children.only(children) as React.ReactElement;


React.cloneElement(child, {anyProp:"newProp" })

this is type of Children

interface ReactChildren {
map<T, C>(children: C | C[], fn: (child: C, index: number) => T):
C extends null | undefined ? C : Array<Exclude<T, boolean | null | undefined>>;
forEach<C>(children: C | C[], fn: (child: C, index: number) => void): void;
count(children: any): number;
only<C>(children: C): C extends any[] ? never : C;
toArray(children: ReactNode | ReactNode[]): Array<Exclude<ReactNode, boolean | null | undefined>>;
}