【问题标题】:TypeError: Cannot read properties of undefined (reading 'style') when the setTimeout runTypeError:setTimeout 运行时无法读取未定义的属性(读取“样式”)
【发布时间】:2021-11-06 02:46:39
【问题描述】:

我正在构建一个图像滑块,如果用户在 5 秒后不使用它,图像就会发生变化。 并且当 5 秒第二次通过时,将显示错误。 谢谢你的帮助

从 'react' 导入 React, { useRef, useState }

从“../assets/before.svg”导入BeforeIcon 从“../assets/next.svg”导入 NextIcon

从“../assets/banner1.jpg”导入 Banner1 从“../assets/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>
)

}

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    setTimeout 在 React 组件中表现不佳。我建议看看这个article by Josh Comeau,他对 setTimeout 的解释和解决方案比我能提供的要好得多。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-04
      • 2017-01-15
      • 2015-01-02
      • 2014-09-18
      • 2021-04-24
      • 2019-06-29
      • 2015-01-13
      • 1970-01-01
      相关资源
      最近更新 更多