React JS Infinite Carousel



我正在React JS中构建一个投资组合应用程序,其中一个页面是关于我的页面。我偶然发现了一个youtube视频,它使用普通JavaScript构建了一个无限旋转木马,在我最初的测试中它是有效的。然而,当我离开"关于我"页面并返回时,它会弹出一个"TypeError: Cannot read property 'style' of null"的提示框。在我的About Me组件"src/组件/我/AboutMe.js: 34"。

import React from "react";
import "./AboutMe.css"
import { Button, 
Fade,
Grow,
Typography } from '@material-ui/core'
import { ArrowBackIos, ArrowForwardIos } from "@material-ui/icons";
import { Background, Adventures, Hobbies } from "./about-me-components/index";
export const AboutMe = () => {
const slider = document.querySelector('.slider-about-me')
const carousel = document.querySelector('.carousel-about-me')
let direction = 1
const stepPrevious = () => {
if (direction === 1) {
slider.appendChild(slider.firstElementChild)
}
direction = -1
console.log("Previous", direction)
carousel.style.justifyContent = 'flex-end'
slider.style.transform = 'translate(33%)'
}
const stepNext = () => {
if (direction === -1) {
slider.prepend(slider.lastElementChild)
}
direction = 1
console.log("Next", direction)
carousel.style.justifyContent = 'flex-start'
slider.style.transform = 'translate(-33%)'
}
const sliderAppend = () => {
if (direction === 1) { 
slider.appendChild(slider.firstElementChild)
} else if (direction === -1) { 
slider.prepend(slider.lastElementChild)
}
slider.style.transition = 'none'
slider.style.transform = 'translate(0)'
setTimeout(() => {slider.style.transition = 'all 0.5s'})
}
return (
<>
<Fade
in={true}
timeout={1500}
>
<div
id='about-me-container'
>
<div className="controls">
<div
className='arrow-span-about-me arrow-left-about-me'
>
<Button
className='button-about-me arrow-about-me'
variant='contained'
onClick={stepPrevious}
>
<ArrowBackIos 
className="arrow-back-about-me"
/>
</Button>
</div>
<div
className='arrow-span-about-me arrow-right-about-me'
>
<Button
className='button-about-me arrow-about-me'
variant='contained'
onClick={stepNext}
>
<ArrowForwardIos 
className="arrow-forward-about-me"
/>
</Button>
</div>
</div>
<div
id="about-me-carousel-container"
>
<div
className='carousel-about-me'
>
<div
className='slider-about-me'
onTransitionEnd={sliderAppend}
>
<section className='text-white'><Background /></section>
<section className='text-white'><Adventures /></section>
<section className='text-white'><Hobbies /></section>
</div>

</div>
</div>
</div>
</Fade>
</>
)
}

我选择这条路线的唯一原因是因为我还没有找到一个半体面的无限旋转木马模块与简单的自定义能力。尽管我更希望这能奏效,但我愿意接受建议和/或解决方案。感谢!

我建议使用useRef而不是document.querySelector

文档。querySelector发生在生命周期之外,使得它返回的内容不可靠,而refs发生在生命周期内。(虽然不会因为像重新渲染这样的生命周期事件而重置。)这确保了ref返回的对象是虚拟DOM当前状态的准确表示。

我想这就是为什么当你离开About页面并返回时遇到上述错误的原因。

下面是一个例子:https://codesandbox.io/s/objective-fast-vhc27?file=/src/modalAndButton.jsx: 531 - 648

相关内容

  • 没有找到相关文章

最新更新