Tengo la App , que es el componente principal y tengo el componente Child :
El componente Child obtiene accesorios llamados items para que pueda reutilizarse según los datos. En el ejemplo hay data , data1 y data2 .
El caso es que quiero configurar una cookie del componente principal, para configurar la cookie necesito el link de propiedad de data2 , pero ya estoy mapeando data2 en el Child component secundario.
¿Qué puedo hacer para obtener el value of the property link en el componente principal para pasarlo como argumento aquí?
<Child onClick={() => handleUpdate('How can I obtain here the string from link of data2?') } items={data2} />Este es el código de ejemplo completo:
import * as React from 'react'; import './style.css'; const data = [ { title: 'hey', description: 'description' }, { title: 'hey1', description: 'description' }, { title: 'hey2', description: 'description' }, ]; const data1 = [ { title: 'hey', description: 'description' }, { title: 'hey1', description: 'description' }, { title: 'hey2', description: 'description' }, ]; const data2 = [ { title: 'hey', link: 'link/hey' }, { title: 'hey1', link: 'link/he1' }, { title: 'hey2', link: 'link/he2' }, ]; export default function App() { const [, setCookie] = useCookie('example'); const handleUpdate = (cookie) => { setCookie(null); setCookie(cookie); }; return ( <div> <h2>App - Parent</h2> <Child items={data} /> <Child items={data1} /> <Child onClick={() => handleUpdate('How can I obtain here the string from link of data2?') } items={data2} /> </div> ); } export function Child({ items }) { return ( <div> <h2>Child</h2> <ul> {items.map((item) => { return ( <> <p>{item.title}</p> <a href={item.link}>Go to title</a> </> ); })} </ul> </div> ); }¡Gracias!
El método de map no cambia la matriz a la que se llama, simplemente devuelve una nueva matriz, la matriz de items no se ve afectada en absoluto aquí, por lo que puede llamarla normalmente así:
return ( <div> <h2>App - Parent</h2> <Child items={data} /> <Child items={data1} /> <Child onClick={() => handleUpdate(data2[0].link) } items={data2} /> </div> ); Además, su componente onClick Child un accesorio de esta manera:
export function Child({ items, handleClick }) { return ( <div onClick={handleClick}> <h2>Child</h2> <ul> {items.map((item) => { return ( <> <p>{item.title}</p> <a href={item.link}>Go to title</a> </> ); })} </ul> </div> ); }Si desea obtener el Child del componente secundario, simplemente puede agregar un parámetro de link en la devolución de llamada:
<Child onClick={(link) => handleUpdate(link)} items={data2} /> Luego, desde el Child , solo necesita llamar al accesorio onClick :
export function Child({ items, onClick }) { // here make sure to add the prop while destructuring <a href={item.link} onClick={() => onClick(item.link)}>Go to title</a>