我正在使用 React 和 Typescript。我有一个充当包装器的反应组件,我希望将其属性复制到其子组件。我正在遵循 React 的使用克隆元素的指南:https://facebook.github.io/react/blog/2015/03/03/react-v0.13-rc2.html#react.cloneelement 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>'.
如何为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 https://github.com/DefinitelyTyped/DefinitelyTyped/blob/949922e0959ccea0cad7a6fa787b63b7d4e67d3f/types/react/index.d.ts#L196这是:
type ReactText = string | number;
type ReactChild = ReactElement<any> | ReactText;
如果你确定child
总是一个ReactElement
然后投射它:
return React.cloneElement(child as React.ReactElement<any>, {
width: this.props.width,
height: this.props.height
});
否则使用isValidElement 类型保护 https://github.com/DefinitelyTyped/DefinitelyTyped/blob/949922e0959ccea0cad7a6fa787b63b7d4e67d3f/types/react/index.d.ts#L351:
if (React.isValidElement(child)) {
return React.cloneElement(child, {
width: this.props.width,
height: this.props.height
});
}
(我以前没有使用过它,但根据定义文件它就在那里)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)