2017-02-15 52 views
7

我正在使用React和Typescript。我有一个作为包装的反应组件,我希望将其属性复制到它的子项。我正在关注React的使用克隆元素的指南:https://facebook.github.io/react/blog/2015/03/03/react-v0.13-rc2.html#react.cloneelement。但是,使用React.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是这样的:

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

如果您确信child总是ReactElement然后投它:

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

否则使用isValidElement type guard

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

(我以前没有使用过它,但根据定义文件它的存在)