繁体   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