【问题标题】:Material UI + Gatsby Google Analytics plugin: "Function components cannot be given refs" warning for Material Ui Link wrapping OutBoundLinkMaterial UI + Gatsby Google Analytics 插件:“Function components cannot be given refs”警告 Material Ui Link wrapping OutBoundLink
【发布时间】:2019-10-26 20:03:54
【问题描述】:

我想将来自 Gatsby Google Analytics 插件的 OutboundLink 组件包装到 Material UI Link 组件中。

我在控制台中收到此错误消息:

index.js:2177 Warning: 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`.
    in OutboundLink (created by ForwardRef)
    in ForwardRef (created by ForwardRef(Typography))
    in ForwardRef(Typography) (created by WithStyles(ForwardRef(Typography)))
    in WithStyles(ForwardRef(Typography)) (created by ForwardRef(Link))
    in ForwardRef(Link) (created by WithStyles(ForwardRef(Link)))
    in WithStyles(ForwardRef(Link)) (created by OutboundLinkThemed)
    in OutboundLinkThemed (created by Credibility)
    in p (created by ForwardRef(Typography))
    in ForwardRef(Typography) (created by WithStyles(ForwardRef(Typography)))
    in WithStyles(ForwardRef(Typography)) (created by MyOwnComponent)
    ...

Material UI 文档讨论了这个here 并链接到React documentation 以了解如何解决它。

我不知道如何解决这个问题。

我尝试了 this solution,但它不起作用,因为 OutboundLink 没有 innerRef 属性。

我也试过了,但仍然发出警告:

import { Link as MuiLink } from "@material-ui/core";

const ForwardOutboundLink = React.forwardRef((props, ref) => (
  <OutboundLink {...props} ref={ref}>
));

export const OutboundLinkThemed = ({ href, target, rel, caption}) => {

  return (
    <MuiLink
      component={ForwardOutboundLink}
      href={href}
      target={target}
      rel={rel}
      underline="hover"
    >
        {caption}
    </MuiLink>
  );
};

到目前为止,渲染的组件按预期工作,所以我在最后几天忽略了它。但我不能继续在我的应用程序中累积警告。我该如何解决?

【问题讨论】:

    标签: reactjs material-ui gatsby


    【解决方案1】:

    以下内容消除了警告(使用 forwardRef,但ref 放在 OutboundLink 上,因为它不支持它):

    const ForwardOutboundLink = React.forwardRef((props, ref) => (
      <OutboundLink {...props} />
    ));
    

    理想的解决方案是在OutboundLink within the plugin 中修复此问题,使其使用forwardRef,然后在a 标记上指定引用。

    【讨论】:

      猜你喜欢
      • 2016-06-27
      • 2021-08-24
      • 2022-06-13
      • 1970-01-01
      • 2020-06-21
      • 1970-01-01
      • 2023-03-10
      • 2019-11-04
      • 1970-01-01
      相关资源
      最近更新 更多