据我所知,我可以像这样为单个元素使用refs:
const { useRef, useState, useEffect } = React;
const App = () => {
const elRef = useRef();
const [elWidth, setElWidth] = useState();
useEffect(() => {
setElWidth(elRef.current.offsetWidth);
}, []);
return (
<div>
<div ref={elRef} style={{ width: "100px" }}>
Width is: {elWidth}
</div>
</div>
);
};
ReactDOM.render(
<App />,
document.getElementById("root")
);
<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<div id="root"></div>
我如何实现这个元素数组?显然不是这样的:(我知道,即使我没有尝试:)
const { useRef, useState, useEffect } = React;
const App = () => {
const elRef = useRef();
const [elWidth, setElWidth] = useState();
useEffect(() => {
setElWidth(elRef.current.offsetWidth);
}, []);
return (
<div>
{[1, 2, 3].map(el => (
<div ref={elRef} style={{ width: `${el * 100}px` }}>
Width is: {elWidth}
</div>
))}
</div>
);
};
ReactDOM.render(
<App />,
document.getElementById("root")
);
<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<div id="root"></div>
我见过这个,所以才会这样。但是,我仍然不知道如何在这个简单的案例中实现这个建议。
以上所有其他选项都依赖于数组,但这使得事情非常脆弱,因为元素可能会重新排序,然后我们就不跟踪ref属于哪个元素了。
React使用键道具来跟踪项目。因此,如果你按键存储你的引用,就不会有任何问题:
const useRefs = () => {
const refs = useRef<Record<string,HTMLElement | null>>({})
const setRefFromKey = (key: string) => (element: HTMLElement | null) => {
refs.current[key] = element;
}
return {refs: refs.current, setRefFromKey};
}
const Comp = ({ items }) => {
const {refs, setRefFromKey} = useRefs()
const refsArr = Object.values(refs) // your array of refs here
return (
<div>
{items.map(item => (
<div key={item.id} ref={setRefFromKey(item.id)}/>
)}
</div>
)
}
请注意,React在卸载一个项目时,将使用null调用所提供的函数,该函数将在对象中将匹配的键项设置为null,因此所有内容都将是最新的。
ref最初只是一个{current: null}对象。useRef在组件渲染之间保持对该对象的引用。当前值主要用于组件引用,但可以保存任何内容。
在某些时候应该有一个refs数组。如果数组的长度可能在不同的渲染之间变化,数组应该相应地缩放:
const arrLength = arr.length;
const [elRefs, setElRefs] = React.useState([]);
React.useEffect(() => {
// add or remove refs
setElRefs((elRefs) =>
Array(arrLength)
.fill()
.map((_, i) => elRefs[i] || createRef()),
);
}, [arrLength]);
return (
<div>
{arr.map((el, i) => (
<div ref={elRefs[i]} style={...}>
...
</div>
))}
</div>
);
这段代码可以通过展开useEffect并将useState替换为useRef来优化,但应该注意的是,在呈现函数中执行副作用通常被认为是一种糟糕的做法:
const arrLength = arr.length;
const elRefs = React.useRef([]);
if (elRefs.current.length !== arrLength) {
// add or remove refs
elRefs.current = Array(arrLength)
.fill()
.map((_, i) => elRefs.current[i] || createRef());
}
return (
<div>
{arr.map((el, i) => (
<div ref={elRefs.current[i]} style={...}>
...
</div>
))}
</div>
);
我使用useRef钩子创建我想独立控制的数据面板。首先我初始化useRef来存储一个数组:
import React, { useRef } from "react";
const arr = [1, 2, 3];
const refs = useRef([])
在初始化数组时,我们观察到它实际上是这样的:
//refs = {current: []}
然后我们应用map函数来创建面板,使用我们将引用的div标签,将当前元素添加到我们的引用中。带有一个按钮的当前数组:
arr.map((item, index) => {
<div key={index} ref={(element) => {refs.current[index] = element}}>
{item}
<a
href="#"
onClick={(e) => {
e.preventDefault();
onClick(index)
}}
>
Review
</a>
})
最后一个函数接收按下按钮的索引,我们可以控制我们想要显示的面板
const onClick = (index) => {
console.log(index)
console.log(refs.current[index])
}
最后,完整的代码是这样的
import React, { useRef } from "react";
const arr = [1, 2, 3];
const refs = useRef([])
//refs = {current: []}
const onClick = (index) => {
console.log(index)
console.log(refs.current[index])
}
const MyPage = () => {
const content = arr.map((item, index) => {
<div key={index} ref={(element) => {refs.current[index] = element}}>
{item}
<a
href="#"
onClick={(e) => {
e.preventDefault();
onClick(index)
}}
>
Review
</a>
})
return content
}
export default MyPage
这对我很管用!希望这些知识对你有用。