如何在材料UI菜单中使用Next.js链接(下一个/链接)组件?

时间:2020-11-05 23:18:58

标签: reactjs material-ui next.js

我通过以下方式具有“材料”用户界面菜单:

<Menu id="simple-menu" anchorEl={anchorEl} keepMounted open={!!anchorEl} onClose={handleClose}>
    <MenuItem onClick={handleClose}>Profile</MenuItem>
    <MenuItem onClick={handleClose}>Log Out</MenuItem>
</Menu>

,并想将next.js Link标签与MenuItem一起使用。最好的方法是什么?

我尝试了以下操作:


以下内容不会呈现<a>标签,但会将href添加到<li>标签。

<Link href={'#'} passHref><MenuItem onClick={handleClose}>Log Out</MenuItem></Link>

我可以在MenuItem中添加一个道具来渲染<a>而不是<li>标签,但是,由于菜单嵌套在<ul>标签下,因此我不确定是否有{{ 1}}是个好主意


以下引发错误

<ul><a>Log Out</a></ul>

错误:元素类型无效:需要一个字符串(对于内置组件)或一个类/函数(对于复合组件),但得到:对象。

6 个答案:

答案 0 :(得分:3)

如另一个答案中所述,在Link标记内提供MenuItem标记将按要求工作,对于样式问题,您必须给出textDecoration: 'none'color: '#000'Link标签中使用,以避免Link文本的下划线和蓝色。

<MenuItem>
   <Link 
      style={{
          textDecoration: 'none', 
          color: '#000'
      }}
      href="#"
   >
    Log Out
   </Link>
</MenuItem>

答案 1 :(得分:1)

您可以将“链接”组件放在“菜单项”组件中。

<MenuItem><Link href="#">Log Out</Link></MenuItem>

答案 2 :(得分:0)

在链接内添加标签

<MenuItem onClick={handleClose} component={<Link href={'#'}><a>Log Out</a></Link>}></MenuItem>

答案 3 :(得分:0)

看看下面的代码是否解决了这个问题,Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object

const ALink = ({ url, linkText }) => <Link href={url}>
    <a>{ linkText }</a>
</Link>    
<MenuItem onClick={handleClose} component={ ALink({url: '#', linkText: 'Log Out') }></MenuItem>

答案 4 :(得分:0)

<MenuItem>内的组件属性为The component used for the root node. Either a string to use a HTML element or a component.,正如材料使用者官方说的那样,它对<li>的显示不正确。

如果要保留<ul><li></li></ul>结构,则必须将<Link>组件嵌套在<MenuItem>组件内。

所以这可能就是您想要的。

<MenuItem onClick={handleClose}>
  <Link href={'#'}>Log Out</Link>
</MenuItem>

答案 5 :(得分:0)

这对我有用,它也禁用了“菜单中带有下划线的常规蓝色链接”:

<MenuItem>
    <Link href="#">
        <a
            style={{
                textDecoration: 'none',
                color: '#000'
            }}
        >
            Profile
        </a>
    </Link>
</MenuItem>