Tengo una serie de componentes de entrada y quiero usar solo una función onChange.
Dentro de un componente de clase, sé que puedo hacer algo como lo siguiente para adaptarme a los diferentes estados:
inputChange(input) { this.setState({ [input.name]: input, }); } ¿Cómo, dentro de un componente funcional, puedo actualizar el estado con solo una función onChange ?
Ejemplo de un componente:
function Form(){ const [selectedClient, updateSelectedClient] = useState(null); const [selectedLocation, updateSelectedLocation] = useState(null); return( <input value={selectedClient} id="selectedClient" name="selectedClient" onChange={???} /> <input value={selectedLocation} id="selectedLocation" name="selectedLocation" onChange={???} /> ); } Thank you for the time!Dado que esta es una forma, combinaría los estados en uno, inicializándolo con un objeto, y luego, cuando se llame al controlador onChange , actualice la propiedad identificada por la id de entrada con el valor.
useEffect se usa aquí para registrar el resultado de actualizar el estado.
const { useEffect, useState } = React; function Example() { const [form, setForm] = useState({}); useEffect(() => { console.log(form); }, [form]) function handleChange(e) { // Grab the id and value from the input const { id, value } = e.target; // Create a new object by spreading out the current form // state, and setting the state property to the new value setForm({ ...form, [id]: value }); } return ( <div> Client: <input value={form.client} id="client" name="client" onChange={handleChange} /> Location: <input value={form.location} id="location" name="location" onChange={handleChange} /> </div> ); } // Render it ReactDOM.render( <Example />, document.getElementById("react") ); input { display: block; } <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>use el mismo método que usó en la clase, la diferencia es que combina el cliente y la ubicación en un objeto que representará el estado, y aprovecha las id :
const {useState} = React; function Form(){ const [selectedClientOrLocation,setSelectedClientOrLocation] = useState({ selectedClient:"", selectedLocation:"" }) const handleChange = (e) =>{ setSelectedClientOrLocation({...selectedClientOrLocation,[e.target.id]:e.target.value}) } return( <form> <label htmlFor="selectedClient"> Client <input value={selectedClientOrLocation.selectedClient} id="selectedClient" name="selectedClient" onChange={handleChange} /> </label> <br/> <label htmlFor="selectedLocation"> Location <input value={selectedClientOrLocation.selectedLocation} id="selectedLocation" name="selectedLocation" onChange={handleChange} /> </label> </form> ) } ReactDOM.render(<Form/>,document.getElementById('root')) <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <div id="root"></div>