![](/img/trans.png)
[英]How to send array of objects data from child component to parent component and store in the parent object using react hooks?
[英]How to send a property from an array of object from a child component to the parent component?
我有App
,這是父組件,我有Child
組件:
Child
組件獲取一個稱為items
的道具,因此可以根據數據重用它。 它的例子有data
, data1
和data2
。
問題是我想從父組件設置一個 cookie,設置 cookie 我需要來自data2
的屬性link
,但我已經在Child component
中映射data2
。
我可以做些什么來獲取父組件value of the property link
以將其作為參數傳遞:
<Child
onClick={() =>
handleUpdate('How can I obtain here the string from link of data2?')
}
items={data2}
/>
這是整個示例代碼:
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>
);
}
謝謝!
如果你想從Child
組件中獲取鏈接,你可以簡單地在回調中添加一個link
參數:
<Child
onClick={(link) => handleUpdate(link)}
items={data2}
/>
然后從Child
你只需要調用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>
map
方法不會改變它被調用的數組,它只是返回一個新數組,這里的items
數組根本不會受到影響,所以你可以像這樣正常調用它:
return (
<div>
<h2>App - Parent</h2>
<Child items={data} />
<Child items={data1} />
<Child
onClick={() =>
handleUpdate(data2[0].link)
}
items={data2}
/>
</div>
);
此外,您的Child
組件需要接受onClick
函數作為道具,如下所示:
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>
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.