[英]Map child refs into parent array
我試圖 map 一個子數組,但在我這樣做時為它們分配一個參考,這樣我就可以從父級中跟蹤它們的位置。
但是,我需要將每個 ref 存儲在一個數組中。
我嘗試了以下,但我得到了一個包含數組的 ref 。 我怎樣才能修改它以獲得一個refs 數組?
這樣我就可以使用getBoundingClientRect()
掛鈎跟蹤元素位置
export default function ({ children }) => {
const itemsRef = useRef([]);
console.log(itemsRef);
// returns a ref containing an array
// {current: Array(5)}
// How could I modify what I am doing
// to to instead return an array of refs?
// something like:
// [{current: HTMLDivElement}, {current: HTMLDivElement}, .....]
return (
<>
{React.Children.map(children, (child, index) =>
React.cloneElement(child, {
ref: (ref) => (
<Item ref={(itemsRef.current[index] = ref)} key={index}>
{child}
</Item>
)
})
)}
</>
);
};
首先創建 refs(與您的數組大小相同)並將其傳遞給您的組件。 我檢查了 childrenLength,因為它可能會在渲染之間發生變化。
export default function ({ children }) => {
const itemsRef = useRef([]);
const childrenLength = itemsRef;
if (itemsRef.current.length != childrenLength) {
itemsRef.current = Array(arrLength).fill().map((_, i) => itemsRef.current[i] || createRef());
}
return (
<>
{React.Children.map(children, (child, index) =>
React.cloneElement(child, {
ref: (ref) => (
<Item ref={itemsRef.current[index]} key={index}>
{child}
</Item>
)
})
)}
</>
);
};
這應該很容易
這是我將如何做的一個例子。
export default function({children}: {children: React.ReactNode[]}) => { const itemsRef = useRef([]); console.log(itemsRef); refLoaded = () => { if (itemsRef.current.length == children.length) { // all ref are loaded, do you work here } } return ( <> { children.map((child, index) => ( <Item ref = {(c) => { if (c) itemsRef.current[index] = c; } key = { index } onLayout={refLoaded}> {child} </Item> ) ) } </> ); };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.