admin管理员组文章数量:1315792
I got this error:
Type 'ForwardedRef<unknown>' is not assignable to type 'LegacyRef<HTMLDivElement>'
import React from "react";
const Other = React.forwardRef((props, ref) => {
return (
<div ref={ref}>
<h1>Other</h1>
</div>
);
});
export default Other;
Is this the right usage?
Demo: =/src/Other.tsx:0-172
I got this error:
Type 'ForwardedRef<unknown>' is not assignable to type 'LegacyRef<HTMLDivElement>'
import React from "react";
const Other = React.forwardRef((props, ref) => {
return (
<div ref={ref}>
<h1>Other</h1>
</div>
);
});
export default Other;
Is this the right usage?
Demo: https://codesandbox.io/s/summer-shadow-5ul13e?file=/src/Other.tsx:0-172
Share Improve this question edited Dec 26, 2022 at 7:04 ghybs 53.4k6 gold badges86 silver badges114 bronze badges asked Dec 26, 2022 at 6:35 Tina GlennTina Glenn 1251 silver badge9 bronze badges 5-
in App.ts try
const myRef = useRef<HTMLDivElement>();
– Layhout Commented Dec 26, 2022 at 6:44 - I tried this stackoverflow./questions/66963289/… but doesn't work – Tina Glenn Commented Dec 26, 2022 at 6:44
- @Layhout not working – Tina Glenn Commented Dec 26, 2022 at 6:45
- i opened your demo, there's no error. – Layhout Commented Dec 26, 2022 at 6:51
-
in App.ts, i imported
useEffect
and addeduseEffect(()=>{console.log(myRef.current)},[])
. and i get the element. – Layhout Commented Dec 26, 2022 at 6:54
2 Answers
Reset to default 8Simply make sure to provide type arguments to forwardRef
, as shown for example here:
import React from "react";
const Other = React.forwardRef<HTMLDivElement, unknown>((props, ref) => {
return (
<div ref={ref}>{/* Okay */}
<h1>Other</h1>
</div>
);
});
Playground Link
Initialise useRef
with null
initially and type <HTMLDivElement>
. Also, apply type <HTMLDivElement>
to forwardRef
as well. Check on mount if ref
is assigned correctly.
Here is the Sandbox Link
本文标签: javascriptUsing forwardRef in other component got type errorStack Overflow
版权声明:本文标题:javascript - Using forwardRef in other component got type error - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741990485a2409009.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论