如何修复React forwardRef(Menu)材质用户界面? [英] Ho to fix React forwardRef(Menu) Material UI?
问题描述
我创建了非常简单的自定义组件 MuiMenu
和 MuiMenuItem
.但是当我显示这些组件时,我看到一个错误:
I created very simple custom components MuiMenu
and MuiMenuItem
. But when I displaying these components I see an error:
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
导入-一切都很好.如何解决?
But if I import directly form @material-ui/core
- all is well. How to fix it?
工作示例: https://codesandbox.io/s/sharp-shadow-bt404?file =/src/App.js
推荐答案
正如错误所言,Material-UI正在使用ForwardRef,您需要在代码中包括它.下面是对MuiMenu和MuiMenuItem组件的修复;
As the error says, Material-UI is using ForwardRef and you need to include that in your code. Below is a fix to your MuiMenu and MuiMenuItem Components;
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出现错误,因此我将其删除.
Also there was an error with the strictmode you used at index so I removed it.
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
here is a link to the fixed sandbox: 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
And here are other links to help you understand a bit more: https://material-ui.com/getting-started/faq/#how-do-i-use-react-router | https://reactjs.org/docs/react-api.html#reactforwardref
这篇关于如何修复React forwardRef(Menu)材质用户界面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!