typescript 向子项提供属性时,如何为 React.cloneElement 分配正确的类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42261783/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to assign the correct typing to React.cloneElement when giving properties to children?
提问by David C
I am using React and Typescript. I have a react component that acts as a wrapper, and I wish to copy its properties to its children. I am following React's guide to using clone element: https://facebook.github.io/react/blog/2015/03/03/react-v0.13-rc2.html#react.cloneelement. But when using using React.cloneElement
I get the following error from Typescript:
我正在使用 React 和 Typescript。我有一个充当包装器的反应组件,我希望将其属性复制到其子项。我正在遵循 React 使用克隆元素的指南:https: //facebook.github.io/react/blog/2015/03/03/react-v0.13-rc2.html#react.cloneelement。但是在使用 using 时,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>'.
How can I assign the correct typing's to react.cloneElement?
如何将正确的类型分配给 react.cloneElement?
Here is an example that replicates the error above:
这是一个复制上述错误的示例:
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());
}
}
回答by Nitzan Tomer
The problem is that the definition for ReactChild
is this:
问题是对于的定义ReactChild
是这样的:
type ReactText = string | number;
type ReactChild = ReactElement<any> | ReactText;
If you're sure that child
is always a ReactElement
then cast it:
如果您确定这child
始终是一个,ReactElement
则将其转换为:
return React.cloneElement(child as React.ReactElement<any>, {
width: this.props.width,
height: this.props.height
});
Otherwise use the isValidElement type guard:
否则使用isValidElement 类型保护:
if (React.isValidElement(child)) {
return React.cloneElement(child, {
width: this.props.width,
height: this.props.height
});
}
(I haven't used it before, but according to the definition file it's there)
(我之前没用过,但根据定义文件它就在那里)