Quiero pasar la referencia de la aplicación a Foo, App y Foo son componentes de funciones, por lo que estoy usando forwardRef() para deformar Foo, pero aparece el error de advertencia TypeError: Cannot add property current, object is not extensible
. Debajo de la identificación de mi código, ¿tengo que cambiar?
import './App.css'; import React, { useState, Component, useEffect, createRef, useRef, forwardRef } from 'react' import ReactDOM from 'react-dom' const Foo=forwardRef((inputRef)=> { const onClick = () => { inputRef.current.focus() } return ( <div> <input type="text" ref={ inputRef }></input> <button onClick={ onClick }>Focus</button> </div> ) }) function App() { const inputRef = createRef() const clicked = () => { inputRef.current.focus() } return ( <div> <Foo ref={inputRef} /> <button onClick={ clicked }>Click Foo</button> </div> ) } export default App;
Defina ref en la función de inicio
const inputRef = useRef(null);
React.forwardRef((props, ref) =>{ return( <button ref={ref}>{props.children}</button> ) };
Aquí está su código editado. He agregado un tipo de referencia que es HTMLInputElement.
type RefType = HTMLInputElement | null; interface PropsType {} const Foo = forwardRef<RefType, PropsType>((props, ref) => { const onClick = () => { if (ref && "current" in ref) { ref.current?.focus(); } }; return ( <div> <input type="text" ref={ref}></input> <button onClick={onClick}>Focus</button> </div> ); }); function App() { const inputRef = createRef<HTMLInputElement>(); const clicked = () => { inputRef.current?.focus(); }; return ( <div> <Foo ref={inputRef} /> <button onClick={clicked}>Click Foo</button> </div> ); } export default App;