我创建了非常简单的自定义组件MuiMenu
和MuiMenuItem
。但是当我显示这些组件时,我看到一个错误:
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)`.
但是,如果我直接从@material-ui/core
导入-一切都很好。如何解决?
工作示例: https://codesandbox.io/s/sharp-shadow-bt404?file=/src/App.js
答案 0 :(得分:1)
如错误所示,Material-UI使用的是ForwardRef,您需要在代码中包括它。以下是对MuiMenu和MuiMenuItem组件的修复;
MuiMenu
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;
MuiMenuItem
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;
此外,您在索引中使用的strictmode出现错误,因此我将其删除。
Index.JS
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
const rootElement = document.getElementById("root");
ReactDOM.render(
<App />,
rootElement
);
这是固定沙箱的链接: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