Tengo un elemento React que representa elementos secundarios con un estado de target
. este estado objetivo puede cambiar en cualquier momento y el padre no tiene acceso en este momento.
const Parent = () => { function getTarget(){ //TODO } return( <Button>get target</Button> {children.map(c=>{ <Child props={props}/> })} ) } const Child = (props) => { //props stuff const [target, setTarget] = useState(null) // this target would be changed by user as they interact. return( //child elements ) }
lo que estoy tratando de hacer es obtener el estado target
del Niño usando el botón en el Padre con las siguientes restricciones:
Puede haber una cantidad variable de elementos Child
, pero solo uno de ellos es visible a la vez.
El botón "obtener objetivo" debe estar en Parent
, el estado "objetivo" debe inicializarse en child
y es desconocido.
porque solo en Child está activo a la vez, una solución que funciona para
return( <Button>get target</Button> <Child props={props}/> )
también está bien
const Parent = () => { const [activeTarget, setActiveTarget] = useState(null); const handleButton = () => { console.log(activeTarget); } return( <Button onClick={handleButton}>get target</Button> {children.map(c=>{ <Child setActiveTarget={setActiveTarget} /> })} ) } const Child = ({setActiveTarget}) => { const [target, setTarget] = useState(null); // when the user interacts call 'setTarget' and 'setActiveTarget' to update both states // update parent state when child mounts useEffect(() => { setActiveTarget(target); }, [target]} // you can additionally add dependencies to update the parent state conditionally return( //child elements ) }