这是我正在使用的ListItem组件:
<ListItem
activeClassName={classes.activeListItem}
className={classes.listItem}
component={NavLink}
to="/dashboard"
>
<ListItemIcon className={classes.listItemIcon}>
<DashboardIcon />
</ListItemIcon>
<ListItemText
classes={{ primary: classes.listItemText }}
primary="Dashboard"
/>
</ListItem>
这会引发以下错误:
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(ListItem)`.
in NavLink (created by ForwardRef(ListItem))
in ForwardRef(ListItem) (created by WithStyles(ForwardRef(ListItem)))
in WithStyles(ForwardRef(ListItem)) (at sidebar/index.tsx:72)
in div (created by ForwardRef(List))
in ForwardRef(List) (created by WithStyles(ForwardRef(List)))
in WithStyles(ForwardRef(List)) (at sidebar/index.tsx:71)
in nav (at sidebar/index.tsx:44)
in Sidebar (created by WithStyles(Sidebar))
in WithStyles(Sidebar) (at dashboard/index.tsx:45)
in div (created by ForwardRef(Paper))
in ForwardRef(Paper) (created by WithStyles(ForwardRef(Paper)))
in WithStyles(ForwardRef(Paper)) (created by ForwardRef(Drawer))
in div (created by ForwardRef(Drawer))
in ForwardRef(Drawer) (created by WithStyles(ForwardRef(Drawer)))
in WithStyles(ForwardRef(Drawer)) (at dashboard/index.tsx:37)
in div (at dashboard/index.tsx:30)
in Dashboard (created by WithStyles(Dashboard))
in WithStyles(Dashboard) (created by Context.Consumer)
in Route (at Routes.tsx:16)
in Switch (at Routes.tsx:10)
in Routes (at App.tsx:15)
in Router (at App.tsx:14)
in ThemeProvider (at App.tsx:13)
in App (at src/index.tsx:7)
当我使用没有NavLink的ListItem时,一切正常:
<ListItem button key={text}>
<ListItemIcon><InboxIcon /></ListItemIcon>
<ListItemText primary={text} />
</ListItem>
因此,我猜想ListItem的component
属性的使用存在问题,但根据目前的知识水平,我无法找出原因:-)
答案 0 :(得分:1)
ListItem
尝试在您通过component
道具指定的组件上specify a ref。
功能组件不支持引用,除非使用React的forwardRef包装引用。
反应路由器的NavLink是一个功能组件,目前还没有被React.forwardRef
包装。
文档here解释了如何包装react-router的Link
(而NavLink
仅包装Link
,以便相同的解决方案可以工作),以便支持接收引用
答案 1 :(得分:0)
ButtonBase组件提供了一个属性来处理此用例:组件。 这是通过将ref附加到组件,并期望该组件将该ref转发到基础DOM节点来实现的。
关注此链接: https://material-ui.com/components/buttons/#third-party-routing-library