React не запускает анимацию для элемента абсолютной позицииCSS

Разбираемся в CSS
Ответить Пред. темаСлед. тема
Anonymous
 React не запускает анимацию для элемента абсолютной позиции

Сообщение Anonymous »

Я пытаюсь добавить переход к HeroTitle и HeroBtn, но, похоже, он не срабатывает. Если я создаю console.log ''element.current'', он показывает, что стили были обновлены, но текущий элемент отображается по реакции, похоже, не меняется.
Я пытаюсь добавить анимацию, похожую на герой-слайдер Судного дня__hero-title https://doomsdayco.com/. Где заголовок скользит снизу, а кнопка исчезает. Но это кажется невозможным, поскольку стили никогда не обновляются, поэтому анимации не происходит.
Ссылка на текущие обновления
Изображение

DOM не обновляется

Изображение

React jsx
import { useState, useEffect, useRef } from "react";
import '../../styles/home.css'
import useSwipe from "../../hooks/useSwipe";

const HeroSlider = () => {
const [imgIndex, setImgIndex] = useState(0);
const intervalTim = useRef(null);
const progressRef = useRef(null);
const heroTitle = useRef(null);
const heroBtn = useRef(null);
const autoplay = false;

const heroImgs = [
'Изображение',
'Изображение',
'Изображение'
]

function showPrevImage() {
setImgIndex((index) => index === 0 ? heroImgs.length - 1 : index - 1);
}

function showNextImage() {
setImgIndex((index) => index === heroImgs.length - 1 ? 0 : index + 1);
}

const { handleTouchStart, handleTouchMove, handleTouchEnd } = useSwipe(showNextImage, showPrevImage);

console.log(imgIndex)

const resetProgressBar = () => {

if (progressRef.current) {
progressRef.current.style.transition = 'none';
progressRef.current.style.width = '0%';
setTimeout(() => {
progressRef.current.style.transition = 'width 5s linear';
progressRef.current.style.width = '105%';
}, 25); // Delay to allow the browser to reset the width
}
};

// This should work
// It's supposed to run on render but the styles don't update
useEffect(() => {
heroTitle.current.style.bottom = 0;
heroBtn.current.style.opacity = 1;
}, [])

useEffect(() => {
//resetProgressBar();
console.log('interval render')
intervalTim.current = autoplay && setInterval(() => {
showNextImage();
resetProgressBar();
}, 5000);

return () => {
console.log('clear')
clearInterval(intervalTim.current)
};
}, [imgIndex]);

return (



{heroImgs.map((imgUrl, i) => (

[img]{imgUrl}
/>




// HeroTitle ref
Title

// HeroButton ref
shop




))}

  • {heroImgs.map((_, i) => (
  • {
    setImgIndex(i)
    }}>


    ))}
left
right





);
}

export default HeroSlider;

CSS
.hero-slider {
width: 100%;
height: 70vh;
position: relative;
margin: 0 0 50px;
font-size: 1rem;
}

.hero-slider__main-img-slider-container {
display: flex;
width: 100%;
height: 100%;
overflow: hidden;
}

.hero-slider__main-img-container {
flex-shrink: 0;
flex-grow: 0;
width: 100%;
height: 100%;
position: relative;
transition: transform 0.3s ease-in-out;
}

.hero-slider__main-img {
width: 100%;
height: 100%;
object-fit: cover;
display: block;
}

/* ELEMENTS TO ANIMATE */

.hero-slider__hero-text-container {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
padding: 0 0 60px;
}

.hero-slider__hero-text {
max-width: 1300px;
margin: 0 auto;
padding: 0 40px;
border: 2px solid blue;
}

.hero-slider__hero-title-container {
border: 2px solid lightseagreen;
position: relative;
height: 100px;
}

/* HERO BUTTON AND HERO TITLE */

.hero-slider__hero-title {
font-size: 4em;
position: absolute;
bottom: -100px;
transition: bottom 1s;
}

.hero-slider__hero-btn {
background-color: black;
color: white;
padding: 10px;
font-size: 1.25em;
opacity: 0;
transition: opacity 1s;
}

/* END OF ELEMENTS TO ANIMATE */

.hero-slider__arrow-btns-container {
position: absolute;
bottom: -20px;
right: 40px;
z-index: 3;
}

.hero-slider__navigation-btns-container {
position: absolute;
bottom: 10px;
left: 0;
right: 0;
z-index: 2;
}

.hero-slider__navigation-btns-list {
max-width: 1300px;
margin: 0 auto;
padding: 0 40px;
display: flex;
gap: 10px;
list-style: none;
}

.hero-slider__navigation-btn {
border: 2px solid #000;
width: 15px;
height: 15px;
border-radius: 50%;
}

.hero-slider__navigation-btn:focus-visible {
outline: 1px solid #000;
}

.hero-slider__navigation-btn:is(:hover, :focus-visible) {
transform: scale(1.1);
}

.hero-slider__prev-btn,
.hero-slider__next-btn {
background-color: black;
color: white;
padding: 10px;
}

.hero-slider__prev-btn {
margin-right: 10px;
}

.hero-slider__arrow-btns-container button:hover {
background-color: red;
}

.hero-slider__progress-bar-container {
overflow: hidden;
position: absolute;
bottom: 0;
left: 0;
width: 100%;
z-index: 1;
height: 50px;
}

.hero-slider__progress-bar {
position: absolute;
bottom: 0;
left: 0;
height: 3px;
background-color: rgba(255, 255, 255, 0.8);
width: 0;
transition: width 5s linear;
border-top-right-radius: 20px;
border-bottom-right-radius: 20px;
}

.hero-slider__progress-bar-inital {
transition: none;
width: 0%;
}

.hero-slider__progress-bar-animation {
transition: width 5s linear;
width: 105%;
}

@media screen and (max-width: 750px) {
.hero-slider__navigation-btns-list {
padding: 0 20px;
}

.hero-slider__hero-text {
padding: 0 20px;
}
}

Я попробовал добавить тайм-аут для учета рендеринга DOM, установил исходный стиль для каждого элемента и установил переменную useState, которая изменилась при нажатии и заставила useEffect визуализировать, добавив ее в массив условий.
Но ни один из них не добавил к элементу никаких стилей и не смог вызвать переход.
1. Добавление тайм-аута
useEffect(() => {
setTimeout(() => {
heroTitle.current.style.bottom = '0';
heroBtn.current.style.opacity = '1';
}, 100);
}, []);

2. Добавление штата
const [test, setTest] = useState(0);

useEffect(() => {
setTimeout(() => {
heroTitle.current.style.bottom = '0';
heroBtn.current.style.opacity = '1';
}, 100);
}, [test]);

// Added click event to image container to test the state theory
{setTest((prev) => prev + 1)}
className="hero-slider__main-img-slider-container"
onTouchStart={handleTouchStart}
onTouchMove={handleTouchMove}
onTouchEnd={handleTouchEnd}
>

3. Также установка исходного стиля
useEffect(() => {
// Set initial state
heroTitle.current.style.bottom = '-100px';
heroBtn.current.style.opacity = '0';

// Set final state after a short delay
setTimeout(() => {
heroTitle.current.style.bottom = '0';
heroBtn.current.style.opacity = '1';
}, 100);
}, []);


Подробнее здесь: https://stackoverflow.com/questions/785 ... te-element
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Css при использовании абсолютной позиции относительно элемента заставляет оба элемента исчезнуть
    Anonymous » » в форуме CSS
    0 Ответы
    17 Просмотры
    Последнее сообщение Anonymous
  • Изменение абсолютной позиции элемента с помощью getBoundingClientRect()
    Гость » » в форуме CSS
    0 Ответы
    26 Просмотры
    Последнее сообщение Гость
  • Как переместить элементы списка матов вниз без использования абсолютной позиции в Angular Material?
    Anonymous » » в форуме CSS
    0 Ответы
    31 Просмотры
    Последнее сообщение Anonymous
  • Проблема относительной/абсолютной позиции в html-почте
    Anonymous » » в форуме CSS
    0 Ответы
    25 Просмотры
    Последнее сообщение Anonymous
  • React Native FlatList с абсолютной позицией позади компонентов
    Anonymous » » в форуме CSS
    0 Ответы
    32 Просмотры
    Последнее сообщение Anonymous

Вернуться в «CSS»