reactjs – 如何在为子项提供属性时为React.cloneElement指定正确的类型?

前端之家收集整理的这篇文章主要介绍了reactjs – 如何在为子项提供属性时为React.cloneElement指定正确的类型?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用React和Typescript.我有一个反应组件作为包装器,我希望将其属性复制到其子代.我正在遵循React的使用clone元素的指南: https://facebook.github.io/react/blog/2015/03/03/react-v0.13-rc2.html#react.cloneelement.但是当使用React.cloneElement时,我从Typescript中得到以下错误
  1. Argument of type 'ReactChild' is not assignable to parameter of type 'ReactElement<any>'.at line 27 col 39
  2. Type 'string' is not assignable to type 'ReactElement<any>'.

如何为react.cloneElement分配正确的输入?

这是一个复制上述错误的示例:

  1. import * as React from 'react';
  2.  
  3. interface AnimationProperties {
  4. width: number;
  5. height: number;
  6. }
  7.  
  8. /**
  9. * the svg html element which serves as a wrapper for the entire animation
  10. */
  11. export class Animation extends React.Component<AnimationProperties,undefined>{
  12.  
  13. /**
  14. * render all children with properties from parent
  15. *
  16. * @return {React.ReactNode} react children
  17. */
  18. renderChildren(): React.ReactNode {
  19. return React.Children.map(this.props.children,(child) => {
  20. return React.cloneElement(child,{ // <-- line that is causing error
  21. width: this.props.width,height: this.props.height
  22. });
  23. });
  24. }
  25.  
  26. /**
  27. * render method for react component
  28. */
  29. render() {
  30. return React.createElement('svg',{
  31. width: this.props.width,height: this.props.height
  32. },this.renderChildren());
  33. }
  34. }
问题是 definition for ReactChild是这样的:
  1. type ReactText = string | number;
  2. type ReactChild = ReactElement<any> | ReactText;

如果您确定该子项始终是ReactElement,则将其强制转换为:

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

否则使用isValidElement type guard

  1. if (React.isValidElement(child)) {
  2. return React.cloneElement(child,{
  3. width: this.props.width,height: this.props.height
  4. });
  5. }

(我之前没有使用它,但根据定义文件,它在那里)

猜你在找的React相关文章