[英]Component's forwardRef children all point to the same ref in an array
I have a function component that takes a variable amount of child (forwardRef) function components.我有一个 function 组件,它采用可变数量的子 (forwardRef) function 组件。 What I would like to achieve is having a ref to each of the child components for animations when a child component is clicked.
我想要实现的是在单击子组件时对动画的每个子组件进行引用。 I have a semi-working solution by creating an array of refs and then cloning all the children and passing an indexed ref to each of them.
我有一个半工作解决方案,方法是创建一个引用数组,然后克隆所有子项并将索引引用传递给每个子项。 The only issue is that all of the refs in the index point to the same (last) child.
唯一的问题是索引中的所有引用都指向同一个(最后一个)孩子。
Here are my components:这是我的组件:
const Navbar = ({children}) => {
const [activeLink, setActiveLink] = useState(0);
const linkRefs = Array(children.length).fill(React.createRef(null));
const handleActiveLinkChange = (index) => {
setActiveLink(index);
console.log(linkRefs[index].current);
}
return (
<nav>
{React.Children.map(children, (child, index) => React.cloneElement(child, {index: index, active: index === activeLink, handleActiveLinkChange, key: "child" + index, ref: linkRefs[index]}))}
</nav>
)
}
const Link = React.forwardRef(({children, active, index, handleActiveLinkChange}, ref) => {
return (
<a href="#" style={linkStyle} onClick={() => handleActiveLinkChange(index)} ref={ref}>
{active ? <b>{children}</b> : children}
</a>
)
});
And assuming I use the components in the following way:并假设我按以下方式使用这些组件:
<Navbar>
<Link>One</Link>
<Link>Two</Link>
<Link>Three</Link>
<Link>Four</Link>
<Link>Five</Link>
</Navbar>
I expect the refs to be:我希望裁判是:
Ref array index![]() |
Ref current![]() |
---|---|
0 ![]() |
One![]() |
1 ![]() |
Two![]() |
2 ![]() |
Three![]() |
3 ![]() |
Four![]() |
4 ![]() |
Five![]() |
But the refs I get are:但我得到的裁判是:
Ref array index![]() |
Ref current![]() |
---|---|
0 ![]() |
Five![]() |
1 ![]() |
Five![]() |
2 ![]() |
Five![]() |
3 ![]() |
Five![]() |
4 ![]() |
Five![]() |
I'm assuming it's something to do with variable scope but I just can't figure out the cause of the issue.我假设它与变量 scope 有关,但我无法找出问题的原因。 I've tried many variations of loops and functions but I'd rather understand the cause than blindly try to find a solution.
我已经尝试了很多循环和函数的变体,但我宁愿了解原因也不愿盲目地尝试找到解决方案。
The issue is with the following line.问题在于以下行。 It creates only one ref and all the array indices refer to that single ref.
它只创建一个 ref,所有数组索引都引用该单个 ref。
const linkRefs = Array(children.length).fill(React.createRef(null));
Instead of the above use the following line which creates new refs for each child as you expect.而不是上面的使用下面的行,它会按照您的预期为每个孩子创建新的引用。
const linkRefs = Array.from({ length: children.length }, () =>
React.createRef(null)
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.