简体   繁体   中英

React AntDesign Menu Sub Item ... make it work like component

For the AntD menu... we utilise <Menu> , <Menu.Item> , <SubMenu> .

But I don't want to use these for navigation but rather for representation. I want to display the attributes of an object using a dropdown as such.

For eg. Apple -> red, fruit; Cucumber -> green, vegetable; would be displayed as a menu with Apple and Cucumber as the Submenu headings, and the dropdowns for each would be red, fruit and green, vegetable respectively.

But I don't want to predefine attributes and Submenu headings. If it was a component (cards for example), I could've made the component render per object, so that if there were 10 objects, 10 cards (for example) would be rendered.

Is it possible to do the same for <SubMenu> and <Menu.Item> where I send the data and it first looks at the key 'Name' and renders as a Submenu Heading and renders attributes individually as Menu Items within the Submenu?

Are there any alternatives I can make use of?


Not sure If my question is very clear... I'm happy to clarify anything if confused.

Not sure if this is what you want

import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Menu } from "antd";

const { SubMenu } = Menu;

const data = [
  {
    Name: "Apple",
    Colour: "red",
    Type: "fruit"
  },
  {
    Colour: "green",
    Type: "vegetable",
    Name: "Cucumber",
    Season: "spring"
  },
  {
    Name: "Book",
    Title: "hello",
    Author: "nick"
  }
];

const Sider = () => {
  const [openKeys, setOpenKeys] = React.useState(["sub1"]);

  const onOpenChange = (keys) => {
    const latestOpenKey = keys.find((key) => openKeys.indexOf(key) === -1);
    if (data.indexOf(latestOpenKey) === -1) {
      setOpenKeys(keys);
    } else {
      setOpenKeys(latestOpenKey ? [latestOpenKey] : []);
    }
  };

  return (
    <Menu mode="inline" onOpenChange={onOpenChange} style={{ width: 256 }}>
      {data.map((each) => (
        <SubMenu key={each.Name} title={each.Name}>
          {Object.entries(each).map(
            ([key, value]) =>
              key !== "Name" && (
                <Menu.Item key={each.Name + "-" + key}>{value}</Menu.Item>
              )
          )}
        </SubMenu>
      ))}
    </Menu>
  );
};

ReactDOM.render(<Sider />, document.getElementById("container"));

CodeSandbox Demo

Let me know if this works for you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM