Material UI + Gatsby Google Analytics(分析)插件:Material Ui Link包装OutBoundLink的“无法给功能组件提供引用”警告

时间:2019-06-12 10:27:06

标签: reactjs material-ui gatsby

我想将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>
  );
};

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

1 个答案:

答案 0 :(得分:1)

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

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

Edit OutboundLink forwardRef

理想的解决方案是将其修复在OutboundLink within the plugin中,以便它使用forwardRef,然后在a标签上指定引用。

相关问题