简体   繁体   中英

TypeError: Cannot read properties of undefined (reading 'style') when the setTimeout run

I am building a image slider, that change of image if the user after 5s don´t use it. And when the 5s second pass the error is display. Thank you for your help

import React, { useRef, useState } from 'react'

import BeforeIcon from "../assests/before.svg" import NextIcon from "../assests/next.svg"

import Banner1 from "../assests/banner1.jpg" import Banner2 from "../assests/banner2.jpg"

import "../styles/banner.css"

export default function 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 doesn't play very well in React components. I would recommend taking a look at this article by Josh Comeau he has a far better explanation and solve for setTimeout than what I could provide.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM