Dav*_*d C 39 typescript ecmascript-6 reactjs
我正在使用React和Typescript.我有一个反应组件充当包装器,我希望将其属性复制到其子组件.我遵循React的使用clone元素的指南:https://facebook.github.io/react/blog/2015/03/03/react-v0.13-rc2.html#react.cloneelement.但是在使用时React.cloneElement我从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>'.
Run Code Online (Sandbox Code Playgroud)
如何为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());
}
}
Run Code Online (Sandbox Code Playgroud)
Nit*_*mer 71
问题是定义ReactChild是这样的:
type ReactText = string | number;
type ReactChild = ReactElement<any> | ReactText;
Run Code Online (Sandbox Code Playgroud)
如果你确定它child总是一个ReactElement然后施放它:
return React.cloneElement(child as React.ReactElement<any>, {
width: this.props.width,
height: this.props.height
});
Run Code Online (Sandbox Code Playgroud)
if (React.isValidElement(child)) {
return React.cloneElement(child, {
width: this.props.width,
height: this.props.height
});
}
Run Code Online (Sandbox Code Playgroud)
(我之前没有使用它,但根据定义文件,它在那里)
这为我解决了:
React.Children.map<ReactNode, ReactNode>(children, child => {
if(React.isValidElement(child)) {
return React.cloneElement(child, props
)
}
}
Run Code Online (Sandbox Code Playgroud)
很简单的解决方案
| 归档时间: |
|
| 查看次数: |
14506 次 |
| 最近记录: |