Estoy implementando un enlace en React y TypesSript que, después de hacer clic, se desplaza al componente correcto, estoy usando useRef Hook.
Pero cuando hago eso, ocurre el error:
Type '{ ref: MutableRefObject<HTMLDivElement | null>; }' is not assignable to type 'IntrinsicAttributes'. Property 'ref' does not exist on type 'IntrinsicAttributes'.A continuación se muestra el código, ¿qué estoy haciendo mal? He probado de varias maneras.
import NewComponent from '../NewComponent'; const titleRef = useRef<null | HTMLDivElement>(null); const handleBackClick = (): any => { titleRef!.current!.scrollIntoView({ behavior: 'smooth' }); }; return ( <Container> <Link onClick={handleBackClick}> Button Text </Link> ... ... ... <SomeComponents /> ... ... ... ... <NewComponent ref={titleRef} /> </Container> ) El NewComponent es un componente simple, como:
const NewComponent = () => { return ( <Container> // Its a simple component </Container> ); }; export default NewComponent;Gracias a cualquiera que pueda ayudarme con esto!
Querría usar forwardRef para decirle a TypeScript que NewComponent puede aceptar una ref que contendrá un elemento div . Así es como lo haría como un ejemplo:
import { forwardRef } from "react"; const NewComponent = forwardRef<HTMLDivElement>((props, ref) => { return <div ref={ref}>{props.children}</div>; }); import { useRef } from "react"; export default function App() { const titleRef = useRef<HTMLDivElement>(null); return ( <div> <NewComponent ref={titleRef} /> </div> ); } Creé este CodeSandbox si quieres jugar con él. También observe que cambio useRef<null | HTMLDivElement>(null) a useRef<HTMLDivElement>(null) .
En React, ref solo puede adjuntarse a DOM, si desea pasarlo a su componente de reacción, debe usar forwardRef
puede encontrar más detalles aquí https://reactjs.org/docs/react-api.html#reactforwardref