TL;DR:希望将listRef.current.clientWidth用于useEffect依赖项。
我想要做一个列表,其中它自动调整其项目的宽度根据列表的宽度。我非常接近,但我无法检测到listRef.current.clientWidth的变化,即<div className="dynamic-list">的宽度。在第一次运行时,listRef为null,所以不能使用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;发布于 2020-01-17 03:01:47
使用诸如@TopW3 3这样的回调ref,我能够解决这个问题。但并不完全满意。这篇文章也帮助我解决了这个问题
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;https://stackoverflow.com/questions/59780409
复制相似问题