我正在实现滑块组件。当用户单击向左或向右箭头时,它将按给定scrollWidth
更改滚动值。我对此实施有疑问:
const Slider = (props) => {
const [scrollValue, setScrollValue] = useState(0)
const [containerDimensions, setWidths] = useState({ offsetWidth: 0, scrollWidth: 0 })
const [activeLeft, setActiveLeftArrow] = useState(false)
const [activeRight, setActiveRightArrow] = useState(true)
...
const checkArrowDisable = () => {
containerDimensions.offsetWidth + scrollValue < containerDimensions.scrollWidth ? setActiveRightArrow(true) : setActiveRightArrow(false)
scrollValue > 0 ? setActiveLeftArrow(true) : setActiveLeftArrow(false)
}
const scrollRight = () => {
const scrollWidth = sliderItem.current.offsetWidth
sliderContainer.current.scrollLeft += scrollWidth
setScrollValue(scrollValue + scrollWidth)
checkArrowDisable()
}
const scrollLeft = () => {
const scrollWidth = sliderItem.current.offsetWidth
sliderContainer.current.scrollLeft -= scrollWidth
setScrollValue(scrollValue - scrollWidth)
checkArrowDisable()
}
在checkArrowDisable
中,将检查滚动和容器宽度值以隐藏/显示左右箭头。问题在于,使用此实现,activeLeft
和activeRight
的状态将在应有的状态下更新一个步骤。checkArrowDisable
函数有什么问题?
设置者不同步。因此,不应在相同的功能或子功能中使用假定的设定值。我的意思是:
const scrollLeft = () => {
const scrollWidth = sliderItem.current.offsetWidth
sliderContainer.current.scrollLeft -= scrollWidth
setScrollValue(scrollValue - scrollWidth) # scrollvalue not necessarily updated yet
checkArrowDisable() # uses scrollvalue which is either updated or not
}
我建议为scrollValue - scrollWidth
使用变量并传递给checkArrowDisable
函数