admin管理员组文章数量:1122846
import React, { useRef } from "react";
export default function test() {
const divs = [1, 2, 3];
const refs = useRef<(HTMLDivElement | null)[]>([]);
return (
<>
{divs.map((v, i) => {
<div ref={(el) => (refs.current[i] = el)}>test</div>;
})}
</>
);
}
i want to do a preloader animation with the divs via the refs. Gives me a ts error when trying to assign refs to the dynamic elements:
Type '(el: HTMLDivElement | null) => HTMLDivElement | null' is not assignable to type 'LegacyRef<HTMLDivElement> | undefined'.
Type '(el: HTMLDivElement | null) => HTMLDivElement | null' is not assignable to type '(instance: HTMLDivElement | null) => void | (() => VoidOrUndefinedOnly)'.
Type 'HTMLDivElement | null' is not assignable to type 'void | (() => VoidOrUndefinedOnly)'.
Type 'null' is not assignable to type 'void | (() => VoidOrUndefinedOnly)'.ts(2322)
import React, { useRef } from "react";
export default function test() {
const divs = [1, 2, 3];
const refs = useRef<(HTMLDivElement | null)[]>([]);
return (
<>
{divs.map((v, i) => {
<div ref={(el) => (refs.current[i] = el)}>test</div>;
})}
</>
);
}
i want to do a preloader animation with the divs via the refs. Gives me a ts error when trying to assign refs to the dynamic elements:
Type '(el: HTMLDivElement | null) => HTMLDivElement | null' is not assignable to type 'LegacyRef<HTMLDivElement> | undefined'.
Type '(el: HTMLDivElement | null) => HTMLDivElement | null' is not assignable to type '(instance: HTMLDivElement | null) => void | (() => VoidOrUndefinedOnly)'.
Type 'HTMLDivElement | null' is not assignable to type 'void | (() => VoidOrUndefinedOnly)'.
Type 'null' is not assignable to type 'void | (() => VoidOrUndefinedOnly)'.ts(2322)
Share
Improve this question
edited Nov 21, 2024 at 21:51
Silas Kierstein
asked Nov 21, 2024 at 21:27
Silas KiersteinSilas Kierstein
112 bronze badges
4
|
1 Answer
Reset to default 0an assignment statement returns the value that was assigned And the ref function shouldn't return anything:
<div ref={(el) => {refs.current[i] = el}}>test</div>
本文标签: reactjsSetting useRefs dynamically reacttypescriptStack Overflow
版权声明:本文标题:reactjs - Setting useRefs dynamically react, typescript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736307070a1933185.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
ref
provided to a parent and just access the child divs withref.current.children
. Keeping track of multiple refs like this is not necessary and could give issues if for some reasondivs
were to change. – moonstar-x Commented Nov 21, 2024 at 21:53