Tengo un componente de enlace y quiero saber cuál es el color del texto. ¿Cómo haría eso en React?
Lo sé con Vanilla JS, puede encontrarlo con element.style.color sin embargo, si realizo algo similar con el siguiente código usando textEl.style.color , obtengo undefined .
export function TextLink({ children, path, inline = false, dash = false }: TextLinkProps) { const textEl = useRef(""); return ( <StyledLink href={path} inline={inline} dash={dash} ref={textEl}> {children} </StyledLink> ); }Puede usar window.getComputedStyle() y pasar el elemento en sí mismo por su ref de la siguiente manera:
const ref = React.useRef(); ... ... ... React.useEffect(() => { const style = window.getComputedStyle(ref.current) console.log(style.color); // rgb(255, 0, 0) }, []);Estás olvidando el 'actual' con tu referencia. escríbelo así:
textEl.current.style.colorMe da rgb(0, 0, 0)
const textEl = React.useRef(null); React.useEffect(() => { if (textEl.current) { console.log(window.getComputedStyle(textEl.current).color) } }, [textEl]) O simplemente use textEl.current.style.color si no necesita uno calculado