Imagina el siguiente escenario:
class Input extends React.Component { render() { return <input value="123" /> } } function App() { const inputRef = React.useRef(); return ( <Input ref={inputRef} /> ); } Quiero acceder al atributo de value de la etiqueta de entrada en el componente de mi App . Sin embargo, inputRef.current.value no está definido.
¿Cómo puedo acceder a los atributos de un componente de clase en React?
Simplemente pasaré la referencia como accesorio y la usaré en el componente de clase.
import React from "react"; class Input extends React.Component { render() { const { inputRef } = this.props; return <input ref={inputRef} name="inputExample" defaultValue="123" />; } } export default function App() { const inputRef = React.useRef(null); const logValue = () => { console.log(inputRef.current ? inputRef.current.value : "No Input found"); }; return ( <div className="App"> <Input inputRef={inputRef} /> <button onClick={logValue} type="button"> Input current value </button> </div> ); }Verifique el sandbox en caso de que quiera ver un ejemplo en vivo: https://codesandbox.io/s/distracted-curran-f6bhbrs-f6bhbr?file=/src/App.js
Debe reenviar la referencia usando forwardRef y establecer la ref en el elemento de input como se muestra a continuación.
class Input extends React.Component { render() { return <input ref={this.props.innerRef} />; } } const MyInput = React.forwardRef((props, ref) => ( <Input innerRef={ref} {...props} /> )); function App() { const inputRef = React.useRef(); const checkValue = () => { console.log(inputRef.current && inputRef.current.value); }; return ( <div> <MyInput ref={inputRef} /> <button onClick={checkValue}>check value</button> </div> ); } ReactDOM.render(<App />, document.querySelector('.react')); <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div class='react'></div> const Input = React.forwardRef((props, ref) => { return <input ref={ref} />; }); function App() { const inputRef = React.useRef(); const checkValue = () => { console.log(inputRef.current && inputRef.current.value); }; return ( <div> <Input ref={inputRef} /> <button onClick={checkValue}>check value</button> </div> ); } ReactDOM.render(<App />, document.querySelector('.react')); <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div class='react'></div>