Empecé a aprender a reaccionar hoy, y estoy tratando de construir una calculadora súper simple, pero aún no estoy familiarizado con la sintaxis y los conceptos básicos de reaccionar. No importa cuánto mire y lea, mi código es así: import './App.css';
const plusaction = (a, b) => { alert(a+b); } function App() { return ( <div className="App"> <input type="number" value={plusaction.a}></input> <input type="number" value={plusaction.b}></input> <button onClick={plusaction}>Result</button> </div> ); } export default App;Como puede ver, se suponía que era una forma simple más una calculadora de acción, pero la alerta me trajo "objeto indefinido". ¿Le importaría corregir mi código y explicar qué hice mal? Agradezco cualquier ayuda que pueda proporcionar.
Primero debe tener un estado para guardar datos
después de eso, debe cambiar su estado con la función onChange de entrada
después de eso, debe leer sus valores del estado
function App() { const [state, setState] = useState({ a: 0, b: 0 }); const plusaction = () => { alert(state.a + state.b); }; return ( <div className="App"> <input type="number" value={state.a} onChange={(e) => setState({ ...state, a: e.target.value })} /> <input type="number" value={state.b} onChange={(e) => setState({ ...state, b: e.target.value })} /> <button onClick={plusaction}>Result</button> </div> ); } export default App;Idealmente, desea almacenar sus valores de entrada en el estado. Aquí he inicializado el estado de input como un objeto que luego se actualizará con b a contienen los valores de las entradas.
plusAction (o handleAdd como lo he llamado aquí) simplemente toma los valores a y b del estado de input y registra la suma en la consola.
Asigne a los elementos de entrada un atributo de name para que puedan identificarse fácilmente.
const { useState } = React; function Example() { // Initialise state const [ input, setInput ] = useState({}); // Destructure the a and b properties from // the state and sum them function handleAdd() { const { a, b } = input; console.log(a + b); } // The onChange listener is attached to the // parent container so we need to check to see // if the changed element is an input function handleChange(e) { if (e.target.matches('input')) { // Destructure the name and value from the input const { name, value } = e.target; // Set the new input state by copying it, and // updating either the a or b property we get from // the name attribute, and then setting its value // Note: the type of the value from an input will // always be a string, so you need to coerce it to // a number first setInput({ ...input, [name]: Number(value) }); } } // The input elements store the value of the // corresponding state property return ( <div onChange={handleChange}> <input name="a" type="number" value={input.a} /> <input name="b" type="number" value={input.b} /> <button onClick={handleAdd}>Result</button> </div> ); } ReactDOM.render( <Example />, document.getElementById('react') ); <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> <div id="react"></div>Documentación adicional
Debe usar useRef para hacer esto. Será más eficiente que useState , que volverá a procesar su aplicación cada vez que cambie su número.
import { useRef } from "react"; function App() { const a = useRef(0); const b = useRef(0); const plusaction = () => { console.log(a.current.value); console.log(b.current.value); alert(parseInt(a.current.value) + parseInt(b.current.value)); }; return ( <div className="App"> <input type="number" ref={a} /> <input type="number" ref={b} /> <button onClick={plusaction}>Result</button> </div> ); } export default App;