gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:34:36 26 4
gpt4 key购买 nike

当将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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com