Traté de convertir javaScript vainilla en React pero no pude obtener el resultado correcto.
Aquí está el código javaScript vainilla :)
var minimum = 1; var maximum = 100; var int1 = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum; var int2 = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum; document.getElementById('question').innerHTML = int1 + " " + "+" + " " + int2; var qanswer = int1 + int2; function fire() { var uanswer = document.getElementById('answer').value; if (uanswer == qanswer) { alert("Nice math skills! Refresh the page to play again!"); } else { alert("WRONG! Don't snooze during math class!") } }Este es el código de reacción :)
export default function App() { const [inputValue, setInputValue ] = useState('') let minimum = 1; let maximum = 10; let int1 = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum; let int2 = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum; var qanswer = int1 + int2; const handleChange = (e) => { setInputValue(e.target.value) } const handleAnswer = () => { if(qanswer === inputValue) { alert('You won') } else { alert('You lose') } } return ( <div className="App"> <h1>Math Game</h1> <h2>{`${int1} + ${int2}`}</h2> <input value={inputValue} onChange={handleChange}/> <button onClick={handleAnswer}>Answer</button> </div> ); }Ahora el problema está aquí cuando escribo la respuesta en el campo de entrada, mi valor de número aleatorio cambia.
Creo que necesitas un estado extra. En este momento, cada vez que el estado cambia debido a un cambio en el valor de entrada, el componente se vuelve a representar, todos los cálculos se vuelven a hacer, y luego eso sucede una y otra vez...
Entonces, su estado objetivo debería ser una matriz en la que pueda almacenar los dos números que desea verificar. Colocamos ese código en una función que se puede volver a llamar después de que se haya presionado el botón.
Inicialmente llamamos a esa función desde un useEffect con una matriz de dependencia vacía, por lo que solo se llama cuando el componente se procesa por primera vez.
En h2 unimos esa matriz para formar una cadena.
En handleAnswer sumamos esos dos elementos para hacer un total y lo comparamos con la cadena (forzada) de la entrada.
const { useEffect, useState } = React; function Example() { // New state const [inputValue, setInputValue ] = useState('') const [ target, setTarget ] = useState([]); // Function to add to the new state const newQuestion = () => { const minimum = 1; const maximum = 10; const int1 = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum; const int2 = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum; // Set the target as an array of two numbers setTarget([int1, int2]); } // Run the function for the first time useEffect(() => newQuestion(), []); const handleChange = (e) => { setInputValue(e.target.value) } const handleAnswer = () => { // Add up the numbers from the state const total = target[0] + target[1]; // Check that total against the number if (total === Number(inputValue)) { alert('You won'); } else { alert('You lose'); } // Call the function again newQuestion(); } return ( <div className="App"> <h1>Math Game</h1> <h2>{target.join(' + ')}</h2> <input value={inputValue} onChange={handleChange}/> <button onClick={handleAnswer}>Answer</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>