Estoy usando React y Typescript. Tengo un componente de reacción que actúa como contenedor y deseo copiar sus propiedades a sus hijos. Estoy siguiendo la guía de React para usar el elemento de clonación: https://facebook.github.io/react/blog/2015/03/03/react-v0.13-rc2.html#react.cloneelement . Pero cuando uso React.cloneElement , aparece el siguiente error de 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>'.¿Cómo puedo asignar la tipificación correcta a react.cloneElement?
Aquí hay un ejemplo que replica el error anterior:
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()); } }El problema es que la definición de ReactChild es esta:
type ReactText = string | number; type ReactChild = ReactElement<any> | ReactText; Si está seguro de que child es siempre un ReactElement , cámbielo:
return React.cloneElement(child as React.ReactElement<any>, { width: this.props.width, height: this.props.height });De lo contrario, use la protección de tipo isValidElement :
if (React.isValidElement(child)) { return React.cloneElement(child, { width: this.props.width, height: this.props.height }); }(No lo he usado antes, pero según el archivo de definición está ahí)
Esto lo resolvió para mí:
React.Children.map<ReactNode, ReactNode>(children, child => { if(React.isValidElement(child)) { return React.cloneElement(child, props ) } }solución bastante simple