Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

129
Visualizações
Useref devolviendo un error al cambiar de vista

Tengo un componente con un método useEffect dentro. Y dentro de este método useEffect, allí creé un useRef para manejar algunos efectos de desplazamiento y animaciones. En particular, const ref = useRef(null); . Funciona bien, sin embargo, al cambiar de vista donde no se usa esta referencia, da un error. Por favor, vea el código y la imagen a continuación:

 import React, { useEffect, useRef, useCallback } from 'react'; import styled from 'styled-components'; import { Anchor, Link } from '../components/AllSvgs'; const Container = styled.div` position: relative; `; const Slider = styled.div` position: fixed; top: 0; right: 2rem; display: flex; justify-content: center; align-items: center; flex-direction: column; transform: translateY(-100%); .chain { transform: rotate(135deg); } `; const PreDisplay = styled.div` position: absolute; top: 0; right: 2rem; `; const AnchorComponent = (props) => { const ref = useRef({ style: { transform: null } }) const hiddenRef = useRef(); useEffect(() => { const handleScroll = () => { let scrollPosition = window.pageYOffset; let windowSize = window.innerHeight; let bodyHeight = document.body.offsetHeight; let diff = Math.max(bodyHeight - (scrollPosition + windowSize)); //diff*100/scrollposition let diffP = (diff * 100) / (bodyHeight - windowSize); ref.current.style.transform = `translateY(${-diffP}%)`; window.pageYOffset > 5 ? (hiddenRef.current.style.display = 'none') : (hiddenRef.current.style.display = 'block'); }; window.addEventListener('scroll', handleScroll); return () => { window.removeEventListener('scroll', handleScroll); ref.current.style.transform = null; } }, []); return ( <Container> <PreDisplay ref={hiddenRef} className='hidden'> <Anchor width={70} height={70} fill='currentColor' /> </PreDisplay> <Slider ref={ref}> {[...Array(props.number)].map((x, id) => { return ( <Link key={id} width={25} height={25} fill='currentColor' className='chain' /> ); })} <Anchor width={70} height={70} fill='currentColor' /> </Slider> </Container> ); }; export default AnchorComponent;

ingrese la descripción de la imagen aquí

Creo que se supone que debo desmontar la referencia, sin embargo, cuando hago esto, no funciona. Por favor ver más abajo:

 return () => { window.removeEventListener('scroll', handleScroll); ref.current = null; }

Alguien sabe que puede ser? Gracias

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

ref.current contiene null en la inicialización. Cuando ref.current.style.transform = 'translateY(${-diffP}%)'; se llama dentro de useEffect , intenta asignar un valor a una propiedad dentro de un objeto, pero no hay ningún objeto, ya que es null .

Para solucionarlo, puede intentar inicializar ref así:.

 const ref = useRef({ style: { transform: null } })
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda