[英]How can i create sections and add items to do sections with React?
讓我們從修復您的 state 開始,現在您只跟蹤id
和title
,但如果您希望每個部分都有不同的項目,您也必須將它們保存在您的 state 中。 您的部分 state 應該看起來像這樣:
const [sections, setSections] = useState([
{
id: 0,
title: 'Test section 1',
items: ['item 1', 'item 2'],
},
{
id: 1,
title: 'Test section 2',
items: ['item a', 'item b'],
},
]);
然后你可以有一個Section
組件來呈現單個部分、它的項目和一個添加新項目的按鈕。 此按鈕將調用您在父級中定義的回調並向下傳遞:
// This is defined in the parent, where your state lives
const addItem = (index, item) => {
const newSections = sections.slice();
newSections[index].items.push(item);
setSections(newSections);
};
然后,您將 map 您的部分放入Section
組件並向下傳遞回調。
{sections.map((section, index) => (
<Section
section={section}
key={section.id}
addItem={(item) => addItem(index, item)}
/>
))}
然后,在您的Section
組件中,您可以調用該回調,傳遞您要添加的項目的值。
這是一個演示: https://stackblitz.com/edit/react-mni8p7?file=src/App.js
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.