[英]TypeError: Cannot read properties of undefined (reading 'style') when the setTimeout run
我正在构建一个图像滑块,如果用户在 5 秒后不使用它,则图像会发生变化。 当 5 秒过去时,显示错误。 感谢您的帮助
import React, { useRef, useState } from 'react'
从“../assests/before.svg”导入 BeforeIcon 从“../assests/next.svg”导入 NextIcon
从“../assests/banner1.jpg”导入Banner1 从“../assests/banner2.jpg”导入Banner2
导入“../styles/banner.css”
导出默认函数 Banner() {
const ImgContainer = useRef()
const [position, setposition] = useState(0)
const w = window.innerWidth
const handleNext = () => {
let newposition = position+1
let move = w*newposition
setposition(newposition)
return(
ImgContainer.current.style.transform = "translateX(-" + move + "px)",
ImgContainer.current.style.transition = "transform, 1s",
console.log(move),
setposition(position+1)
)
}
const handleBefore = () => {
let newposition = position-1
let move = w*newposition
setposition(newposition)
return(
ImgContainer.current.style.transform = "translateX(-" + move + "px)",
ImgContainer.current.style.transition = "transform, 1s",
console.log(ImgContainer.current.style)
)
}
setTimeout(() => {
if (position===0){
handleNext()
}
else {
return(
console.log("slide")
)
}
}, 5000);
return (
<section>
<button onClick={handleBefore}><img src={BeforeIcon} alt="" className="button rigth"/></button>
<div ref={ImgContainer} className="imgcontainer">
<img src={Banner2} alt="" className="bannerimg"/>
<img src={Banner2} alt="" className="bannerimg"/>
<img src={Banner2} alt="" className="bannerimg"/>
<img src={Banner2} alt="" className="bannerimg"/>
<img src={Banner1} alt="" className="bannerimg"/>
<img src={Banner1} alt="" className="bannerimg"/>
<img src={Banner1} alt="" className="bannerimg"/>
</div>
<button onClick={handleNext}><img src={NextIcon} alt="" className="button left"/></button>
</section>
)
}
setTimeout 在 React 组件中表现不佳。 我建议看一下Josh Comeau 的这篇 文章,他对 setTimeout 的解释和解决方法比我能提供的要好得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.