使用 react-router-dom 时,如何避免“功能组件无法提供参考"? [英] How do I avoid 'Function components cannot be given refs' when using react-router-dom?

查看:17
本文介绍了使用 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...

警告:不能为函数组件提供引用.尝试访问这个 ref 会失败.你的意思是使用 React.forwardRef() 吗?

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

检查ForwardRef的render方法.在 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 是一个功能组件,它是 Link 为此目的公开了一个 innerRef 道具.

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://mui.com/getting-started/faq/#how-do-i-use-react-router 链接到 https://mui.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://mui.com/getting-started/faq/#how-do-i-use-react-router which links to https://mui.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆