Me pregunto si hay una forma de actualizar un estado en un componente funcional principal desde un componente secundario usando una función, algo similar al siguiente ejemplo para componentes de clase:
<ParentComponent name={ this.state.name } email={ this.state.email } setValues={ ( state, value ) => { this.setState({ [state] : value }) }} /> <ChildComponent> <input type={ 'text' } value={ this.props.name } onChange={ ( event ) => { this.props.setValues( 'name', event.target.value ) }} /> <input type={ 'email' } value={ this.props.email } onChange={ ( event ) => { this.props.setValues( 'email', event.target.value ) }} /> </ChildComponent>Necesito algo similar en un componente funcional usando Hooks si es posible.
Déjame saber si se requiere más información.
Gracias por adelantado.
al igual que el caso de la clase, pase la función de cambio de estado como accesorios al componente secundario y haga lo que quiera con la función
import React, {useState} from 'react'; const ParentComponent = () => { const[state, setState]=useState(''); return( <ChildConmponent stateChanger={setState} /> ) } const ChildConmponent = ({stateChanger, ...rest}) => { return( <button onClick={() => stateChanger('New data')}></button> ) }Posiblemente pueda implementar algún reductor como lógica.
import React, { useState } from "react"; const ParentComponent = () => { const [count, setCount] = useState(0); const [name, setName] = useState("John"); const [otherState, setOtherState] = useState(false); const changeState = (state, value) => { // Pass state as string switch (state) { case "count": return setCount(value); case "name": return setName(value); case "otherState": return setOtherState(value); } }; return <ChildConmponent stateChanger={changeState} />; }; const ChildConmponent = ({ stateChanger, ...rest }) => { return ( <div> {/* Change count */} <button onClick={() => stateChanger("count", 10)}></button> {/* Chnage name */} <input type="text" onChange={(event) => stateChanger("name", event.target.value)} /> {/* Change other state */} <input type="checkbox" onChange={(event) => stateChanger("otherState", event.target.checked)} /> </div> ); };Sin embargo, realmente no recomendaría este enfoque. Consulte los ganchos useReducer y useContext , que deberían proporcionarle una solución mucho mejor para este problema.
¡Que tengas un lindo día!