Soy nuevo en Reaccionar. Mi pregunta es... Hay campos de entrada y botones en componentes funcionales separados. Cuando el usuario ingresa los datos en los campos de entrada y hace clic en el botón, los datos de la entrada deben mostrarse en la consola. Hay App.js, que es el componente principal, y Input.js (componente secundario) y Submit.js (componente secundario). Submit.js tiene un botón. Importamos Input.js y Submit.js en App.js.
Deberíamos validar los datos de entrada y al hacer clic en el botón Enviar, si los datos no están en el formato correcto, entonces mostrar un error. De lo contrario, consola los datos en formato json en la consola.
Espero que hayas entendido la lógica. Por favor envíe el código para eso. He intentado pensar pero he golpeado. Por favor, ayúdame con el código. Gracias
En aplicación.js
import { useState } from "react"; import Input from "./Input"; import Submit from "./Submit"; export default function App() { const [value, setValue] = useState(""); const handleChange = (event) => { setValue(event.target.value); }; const handleSubmit = () => { console.log(value); // do validation with `value` console.log(JSON.stringify({ error: "" })); // console JSON data on error }; return ( <div> <Input value={value} handleChange={handleChange} /> <Submit handleSubmit={handleSubmit} /> </div> ); }Entrada.js
export default function Input({ value, handleChange }) { return <input type="text" value={value} onChange={handleChange} />; }Enviar.js
export default function Submit({ handleSubmit }) { return ( <button type="submit" onClick={handleSubmit}> Submit </button> ); }la solución más simple será crear un estado en app.js y dar valor de entrada y onChange props mientras le da al botón la función de envío con el valor de estado
import React, { useState } from 'react'; import TextInput from './TextInput'; import SubmitButton from './SubmitButton'; const App = () => { const [inputVal, setInputVal] = useState(null); const [OutPut, setOutPut] = useState({ error: false, errorText:'',correctVal: '' }); const checkInput = () => { if (Number.isInteger(+inputVal) === false)return setOutPut({ ...OutPut, error: true, errorText: 'Input field accept only numbers' }); //Add API call after validating at below else condition else setOutPut({ ...OutPut, error: false, correctVal: inputVal }); }}; return ( <div> <TextInput setInputVal={setInputVal} /> <SubmitButton checkInput={checkInput} /> {OutPut.error === true ? ( <h3 style={{ color: 'red' }}>{OutPut.errorText}</h3> ) : (OutPut.error===false && OutPut.correctVal !==''?( <h3 style={{ color: 'blue' }}>Your input is : {OutPut.correctVal}</h3> ):'')} </div> ); }; export default App;2. Botón
import React from 'react'; const SubmitButton = ({ checkInput }) => {return <button type='button' onClick={() => checkInput()}>Submit</button>}; export default SubmitButton;3.Entrada.js
import React from 'react'; const TextInput = ({ setInputVal }) => { return ( <input type='text' placeholder='Type anything here to see if your input is number' onChange={(e) => setInputVal(e.target.value)} /> ); }; export default TextInput;