如何修复 React forwardRef(Menu) Material UI?

itw*_*aze 7 reactjs material-ui

我创建了非常简单的自定义组件MuiMenuMuiMenuItem. 但是当我显示这些组件时,我看到一个错误:

Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

Check the render method of `ForwardRef(Menu)`.
Run Code Online (Sandbox Code Playgroud)

但是如果我直接导​​入表单@material-ui/core- 一切都很好。如何解决?

工作示例:https : //codesandbox.io/s/sharp-shadow-bt404?file=/src/App.js

mw5*_*509 7

正如错误所说,Material-UI 正在使用 ForwardRef,您需要将其包含在您的代码中。下面是对您的 MuiMenu 和 MuiMenuItem 组件的修复;

菜单

import React from "react";
import Menu from "@material-ui/core/Menu";


const MuiMenu = React.forwardRef((props, ref) => {
  return <Menu  ref={ref} {...props} />;
});

export default MuiMenu;
Run Code Online (Sandbox Code Playgroud)

菜单项

import React from "react";
import MenuItem from "@material-ui/core/MenuItem";

const MuiMenuItem = React.forwardRef((props, ref) => {
  return <MenuItem  ref={ref} {...props} />;
});

export default MuiMenuItem;
Run Code Online (Sandbox Code Playgroud)

您在索引中使用的严格模式也有错误,所以我将其删除。

索引.JS

import React from "react";
import ReactDOM from "react-dom";

import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(
    <App />,
  rootElement
);
Run Code Online (Sandbox Code Playgroud)

这是固定沙箱的链接:https : //codesandbox.io/s/hopeful-thunder-u6m2k

这里有其他链接可以帮助您了解更多:https : //material-ui.com/getting-started/faq/#how-do-i-use-react-router | https://reactjs.org/docs/react-api.html#reactforwardref