使用react-router-dom时如何避免“无法给功能组件提供引用"? [英] How do I avoid 'Function components cannot be given refs' when using react-router-dom?
问题描述
我有以下内容(使用Material UI)...
I have the following (using Material UI)....
import React from "react";
import { NavLink } from "react-router-dom";
import Tabs from "@material-ui/core/Tabs";
import Tab from "@material-ui/core/Tab";
function LinkTab(link){
return <Tab component={NavLink}
to={link.link}
label={link.label}
value={link.link}
key={link.link}
/>;
}
在新版本中,这会导致以下警告...
In the new versions this causes the following warning...
警告:不能为功能组件提供引用.尝试访问 该裁判将失败.您是要使用React.forwardRef()吗?
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
检查ForwardRef
的渲染方法.
在NavLink中(由ForwardRef创建)
Check the render method of ForwardRef
.
in NavLink (created by ForwardRef)
我尝试更改为...
function LinkTab(link){
// See https://material-ui.com/guides/composition/#caveat-with-refs
const MyLink = React.forwardRef((props, ref) => <NavLink {...props} ref={ref} />);
return <Tab component={MyLink}
to={link.link}
label={link.label}
value={link.link}
key={link.link}
/>;
}
但是我仍然得到警告.我该如何解决这个问题?
But I still get the warning. How do I resolve this issue?
推荐答案
NavLink
from react-router
is a function component that is a specialized version of Link which exposes a innerRef
prop for that purpose.
// required for react-router-dom < 6.0.0
// see https://github.com/ReactTraining/react-router/issues/6056#issuecomment-435524678
const MyLink = React.forwardRef((props, ref) => <NavLink innerRef={ref} {...props} />);
您还可以在我们的文档中搜索react-router
,从而将您引至 https://material-ui.com/components/buttons/#third-party-routing-library .最后一个链接提供了一个有效的示例,并解释了这在React-router v6中将如何改变
You could've also searched our docs for react-router
which leads you to https://material-ui.com/getting-started/faq/#how-do-i-use-react-router which links to https://material-ui.com/components/buttons/#third-party-routing-library. The last link provides a working example and also explains how this will likely change in react-router v6
这篇关于使用react-router-dom时如何避免“无法给功能组件提供引用"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!