簡體   English   中英

我如何創建部分並添加項目以使用 React 做部分?

[英]How can i create sections and add items to do sections with React?

我想知道如何創建一個部分,我所說的部分是這樣的

在此處輸入圖像描述

在這些部分中,每個按鈕都會添加諸如項目 1、項目 2 之類的內容。

讓我們從修復您的 state 開始,現在您只跟蹤idtitle ,但如果您希望每個部分都有不同的項目,您也必須將它們保存在您的 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM