2017-02-15 25 views
7

React ve Typescript kullanıyorum. Sarmalayıcı olarak davranan bir tepki bileşenim var ve özelliklerini çocuklarına kopyalamak istiyorum. React'ın klon elemanı kullanma kılavuzunu takip ediyorum: https://facebook.github.io/react/blog/2015/03/03/react-v0.13-rc2.html#react.cloneelement. Ama yazılardan aşağıdaki hatayı alıyorum React.cloneElement kullanarak kullanırken:Çocuklara özellikler verirken React.cloneElement öğesinin doğru yazımı nasıl atanır?

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>'. 

nasıl doğru yazarak en react.cloneElement için atayabilirsiniz? İşte

yukarıdaki hatayı kopyalayan bir örnektir:

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()); 
    } 
} 

cevap

12

sorun definition for ReactChild bu olmasıdır: Eğer child daima ardından ReactElement olduğundan eminseniz

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

döküm:

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

Aksi kullanmak isValidElement type guard:

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

(Daha önce kullandım, ama tanım dosyası orada olduğunu göre değil)