import { useState } from "react"; import "./styles.css"; function App() { const [InputVal, setInputVal] = useState(); const [ShowDiv, setShowDiv] = useState( <div> <p>Hello world. This is default "Show Div" value</p> </div> ); const ChangeDivFunc = () => { setShowDiv( <div> <p style={{ color: "red" }}> Hello World. This is updated "Show Div" value </p> <input onChange={getInputval} type="text" /> <br /> <br /> <button onClick={AlertVal}>Show Input Value</button> </div> ); }; const getInputval = (val) => { setInputVal(val.target.value); }; const AlertVal = () => { alert(InputVal); }; return ( <div className="App"> <h1>Example</h1> <br /> <button onClick={ChangeDivFunc}>Change Div</button> {ShowDiv} </div> ); } export default App;Flujo de código:
Problema: Devuelve indefinido en lugar del valor del campo de entrada .
Estoy tratando de obtener el valor del campo de entrada cuando se hace clic en el botón Mostrar valor de entrada. Pero no estoy obteniendo los resultados deseados.
Aquí está el enlace de Sandbox: haga clic para obtener el código
No almacene el nodo html dentro del estado. Simplemente puede almacenar solo un valor booleano para cambiar entre qué nodo mostrar. No estoy muy seguro, pero puede provocar un comportamiento extraño, ya que React depende en gran medida internamente del árbol de interfaz de usuario DOM/HTML (ver Estado de gestión ).
Prueba esto en su lugar:
import { useState } from "react"; import "./styles.css"; function App() { const [inputVal, setInputVal] = useState(""); // initialize as empty string. const [showDiv, setShowDiv] = useState(false); const changeDivFunc = () => { setShowDiv(true); }; const getInputVal = (event) => { // The arg is Event object, not val setInputVal(event.target.value); }; const alertVal = () => { alert(inputVal); }; return ( <div className="App"> <h1>Example</h1> <br /> <button onClick={changeDivFunc}>Change Div</button> { showDiv? ( <div> <p style={{ color: "red" }}> Hello World. This is updated "Show Div" value </p> <input value={inputVal} onChange={getInputVal} type="text" /> <br /> <br /> <button onClick={alertVal}>Show Input Value</button> </div> ) : ( <div> <p>Hello world. This is default "Show Div" value</p> </div> ) } </div> ); } export default App;