reactjs - forwardRef : Property 'ref' does not exist on type 'IntrinsicAttributes' 的泛型错误

标签 reactjs typescript

当将forwardRef与泛型一起使用时,我得到类型'IntrinsicAttributes'上不存在属性'children'类型'IntrinsicAttributes'上不存在属性'ref' .

https://codesandbox.io/s/react-typescript-0dt6d?fontsize=14

上面 CodeSandbox 链接中的相关代码复制到此处:

interface SimpleProps<T extends string>
  extends React.HTMLProps<HTMLButtonElement> {
  random: T;
}

interface Props {
  ref?: React.RefObject<HTMLButtonElement>;
  children: React.ReactNode;
}

function WithGenericsButton<T extends string>() {
  return React.forwardRef<HTMLButtonElement, Props & SimpleProps<T>>(
    ({ children, ...otherProps }, ref) => (
      <button ref={ref} className="FancyButton" {...otherProps}>
        {children}
      </button>
    )
  );
}

() => (
  <WithGenericsButton<string> ref={ref} color="green">
    Click me! // Errors: Property 'children' does not exist on type 'IntrinsicAttributes'
  </WithGenericsButton>
)

这里建议了一个潜在的解决方案,但不确定如何在这种情况下实现: https://github.com/microsoft/TypeScript/pull/30215 (从 https://stackoverflow.com/a/51898192/9973558 找到)

最佳答案

因此,这里的主要问题是您在渲染中返回 React.forwardRef 的结果,这不是渲染函数的有效返回类型。您需要将forwardRef结果定义为它自己的组件,然后将其呈现在您的WithGenericsButton高阶组件中,如下所示:

import * as React from "react";

interface SimpleProps<T extends string> {
  random: T;
}

interface Props {
  children: React.ReactNode;
  color: string;
}

function WithGenericsButton<T extends string>(
  props: Props & SimpleProps<T> & { ref: React.Ref<HTMLButtonElement> }
) {
  type CombinedProps = Props & SimpleProps<T>;
  const Button = React.forwardRef<HTMLButtonElement, CombinedProps>(
    ({ children, ...otherProps }, ref) => (
      <button ref={ref} className="FancyButton" {...otherProps}>
        {children}
      </button>
    )
  );
  return <Button {...props} />;
}

const App: React.FC = () => {
  const ref = React.useRef<HTMLButtonElement>(null);
  return (
    <WithGenericsButton<string> ref={ref} color="green" random="foo">
      Click me!
    </WithGenericsButton>
  );
};

如果您将其放入沙箱或 Playground 中,您将看到 props 现在已正确键入,包括 Trandom 属性

关于reactjs - forwardRef : Property 'ref' does not exist on type 'IntrinsicAttributes' 的泛型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57750777/

相关文章:

javascript - 测试componentDidUpdate enzyme reactjs

javascript - 如何在谷歌地图中心制作固定标记以使用react?

javascript - 在 JSX sourcemap 中保留由 Webpack 设置的范围内的变量名称

javascript - 内存路由器类型错误 : Cannot read property 'pathname' of undefined

reactjs - 如何在具有 protected 功能的 React Router 中映射路由?

reactjs - 使用 Standardjs no-unused-vars

javascript - Firebase Javascript/Typescript map 兼容性

javascript - 使用 Typescript 自定义光标

javascript - 将 NodeJS 项目移动到 TypeScript 的过程

angular - 测试模块无法解析正在测试的模块 [Angular4、Karma、Jasmine]