admin管理员组

文章数量:1334923

I want to implement context menus like this:

But I can only achieve this so far: =/src/DataGridTest.tsx

The contextmenu event fired after clicking on a cell (or row).

But I want to immediately fire the contextmenu event.

What should I do?

I want to implement context menus like this: https://fancygrid./samples/miscellaneous/context-menu

But I can only achieve this so far: https://codesandbox.io/s/xenodochial-snow-pz1fr?file=/src/DataGridTest.tsx

The contextmenu event fired after clicking on a cell (or row).

But I want to immediately fire the contextmenu event.

What should I do?

Share Improve this question edited Jul 23, 2021 at 6:30 ehiller 1,56721 silver badges35 bronze badges asked Jul 22, 2021 at 5:30 mochi0708mochi0708 231 silver badge3 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

In addition to Chris Wong's answer, you can also do the following:

<DataGridPremium
        rows={rows}
        slotProps={{
          row: {
            onContextMenu: (e) => handleRowContextMenu(e),
            style: { cursor: 'context-menu' },
          },
        }}

        {...props}
      />

Then, you can get the row:

  const handleRowContextMenu = (event: React.MouseEvent<HTMLDivElement>) => {
    event.preventDefault();

    if (!event.currentTarget) {
      return;
    }
    const rowId = Number((event.currentTarget as HTMLDivElement).getAttribute('data-id'));

    const record = rows.find((row) => row.id === rowId);

    if (!record) {
      return;
    }
    
    // open a context menu
    setContextMenu(
      contextMenu === null ? { mouseX: event.clientX, mouseY: event.clientY, record } : null
    );
  };

Use onContextMenu on the parent:

const onContextMenu = (e: React.SyntheticEvent): void => {
  let target = e.target as HTMLElement;
  console.log(target.innerHTML);
};
...
<div style={{ height: 300, width: "100%" }} onContextMenu={onContextMenu}>
...

There is a demo.

本文标签: javascriptHow to implement context menus on MatrialUI DataGridStack Overflow