我正在使用React和Typescript。我有一个充当包装器的react组件,我希望将其属性复制到其子级。我正在遵循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()); } }
问题是它的定义ReactChild是这样的:
ReactChild
type ReactText = string | number; type ReactChild = ReactElement<any> | ReactText;
如果您确定child始终是a,ReactElement则进行强制转换:
child
ReactElement
return React.cloneElement(child as React.ReactElement<any>, { width: this.props.width, height: this.props.height });
否则,请使用isValidElement类型的guard:
if (React.isValidElement(child)) { return React.cloneElement(child, { width: this.props.width, height: this.props.height }); }
(我以前没有使用过,但是根据定义文件,它在那里)