TL;DR: Want to use listRef.current.clientWidth for useEffect dependency.
我想制作一个列表,它会根据列表的宽度自动调整其项目的宽度。我已经很接近了,但我无法检测到 listRef.current.clientWidth
的变化这是 <div className="dynamic-list">
的宽度。第一次运行时 listRef 为空,所以我不能有 listRef.current.clientWidth
对于 useEffect 依赖项。 listRef ? listRef.current.clientWidth : null
对于依赖关系也不适用于 use simple dependency warning
。
const DynamicList = ({
dataSource, renderItem, itemMaxWidth, itemHeight,
margin, height = 500, width = 700 }) => {
const windowWidth = useWindowDimensions().width;
const [itemStyle, setItemStyle] = useState({ width: itemMaxWidth, height: itemHeight });
const [currentWidth, setCurrentWidth] = useState(null);
const listRef = useRef();
useEffect(() => {
if (listRef) {
const num = Math.floor(listRef.current.clientWidth / itemMaxWidth)
console.log(
num,
listRef.current.clientWidth,
listRef.current
)
setItemStyle((pre) => ({
...pre,
height: itemHeight,
margin: margin,
width: (listRef.current.clientWidth / num) - (margin ? margin * 2 : 0),
}))
}
}, [listRef, windowWidth, itemMaxWidth, margin, itemHeight, width])
return (
<div
className="dynamic-list"
ref={listRef}
style={{
width: width,
height: height
}}
>
{
dataSource.map((item, index) => {
return (
<div style={itemStyle} key={index}>
{renderItem(item, index)}
</div>
)
})
}
</div>
);
};
export default DynamicList;
- 如果有任何能让这一切变得更好的建议,我们将不胜感激。
最佳答案
使用像@TopW3所说的回调引用,我能够解决这个问题。但并不完全满意。 Article that also helped me solve the problem
const DynamicList = ({
dataSource, renderItem, itemMaxWidth, itemHeight,
margin, height = 500, width = 700 }) => {
const windowWidth = useWindowDimensions().width; // 윈도우 크기 변화 감지용
const [itemStyle, setItemStyle] = useState({
width: itemMaxWidth,
height: itemHeight,
margin: margin
});
const [listWidth, setListWidth] = useState(null);
const onListRefSet = useCallback((ref) => {
if (ref)
if (ref.current)
setListWidth(ref.current.clientWidth);
})
useEffect(() => {
if (listWidth) {
const num = Math.floor(listWidth / itemMaxWidth);
setItemStyle((pre) => ({
...pre,
width: (listWidth / num) - (margin ? margin * 2 : 0),
}))
}
}, [listWidth, itemMaxWidth, margin, itemHeight, windowWidth])
return (
<div
className="dynamic-list"
ref={onListRefSet}
style={{
width: width,
height: height,
minWidth: itemMaxWidth
}}
>
{
dataSource.map((item, index) => {
return (
<div style={itemStyle} key={index}>
{renderItem(item, index)}
</div>
)
})
}
</div>
);
};
export default DynamicList;
关于javascript - 使用最初 undefined variable 的属性来实现 useEffect 依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59780409/