2017-02-15 4 views
7

私はReactとTypescriptを使用しています。私はラッパーとして動作する反応コンポーネントを持っており、そのプロパティをその子にコピーしたいと考えています。私はクローン要素を使用するためのReactのガイドに従っています:https://facebook.github.io/react/blog/2015/03/03/react-v0.13-rc2.html#react.cloneelementReact.cloneElementを使用して使用した場合でも、私は活字体から次のエラーを取得する:React.cloneElementに正しい型を割り当てる方法は、子にプロパティを渡す場合ですか?

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

答えて

12

問題をdefinition for ReactChildがこのであるということです:あなたはchildは常に、その後ReactElementであることを確認している場合

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

キャストする:

は、そうでない場合はisValidElement type guardを使用します。

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

(私は前にそれを使用していないが、定義ファイルに基づいて、それはあります)

関連する問題