Mos*_*she 6 javascript reactjs material-ui next.js
我在 Next.JS 中使用 Material-UI。我想使用Material-UI Link 组件,以便我可以访问variant和其他与 Material UI 相关的 API props。同时,我需要使用NextJS Link 组件进行页面之间的链接。
我想知道,我如何将它们两者一起使用,以便我可以获得 NextJS Link 组件的链接优势以及 MaterialUI 链接组件的样式优势。
理想情况下,我想创建我自己的 Link 组件,将它们中的两个组合到我的单个组件中,以便我可以在我的项目中的任何需要的地方使用它。
有任何想法吗?
谢谢。
Spe*_*051 23
我不同意所有已接受的答案。这是我认为最简洁、最清晰的。
<Button // MUI Button
href="/employees"
LinkComponent={Link} // NextJS Link
>
Manage Employees
</Button>
Run Code Online (Sandbox Code Playgroud)
此模式适用于大多数(所有?)MUI 组件。
Shi*_*kyo 22
从 NextJS 13 开始,默认'next/link'公开a,这意味着您不再需要在链接组件内渲染锚元素。这使得与 MUI 的集成变得更加容易
import { createTheme } from '@mui/material/styles';
import NextLink from 'next/link';
import { forwardRef } from 'react';
const LinkBehaviour = forwardRef(function LinkBehaviour(props, ref) {
return <NextLink ref={ref} {...props} />;
});
const theme = createTheme({
components: {
MuiLink: {
defaultProps: {
component: LinkBehaviour
}
},
MuiButtonBase: {
defaultProps: {
LinkComponent: LinkBehaviour
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
然后就可以'@mui/material/Link'像平常一样导入和使用了。
或者,您可以在使用链接时设置组件:
<Link component={LinkBehaviour} href="/go-here">
Click me!
</Link>
Run Code Online (Sandbox Code Playgroud)
这种方法可能有一些警告,到目前为止这对我有用。尽管可能存在一些开销,但它似乎也可以正确处理外部链接。
小智 18
Updated Answer
Before Next.js 13
import NextLink from 'next/link'
import Link from '@mui/material/Link';
// ...
<NextLink href="/" passHref>
<Link variant="body2">Your Link</Link>
</NextLink>
Run Code Online (Sandbox Code Playgroud)
From Next.js 13
import NextLink from 'next/link'
import Link from '@mui/material/Link';
<Link href="/" component={NextLink} variant="body2">
Your link
</Link>
Run Code Online (Sandbox Code Playgroud)
Raj*_*jiv 13
Link接受component结合了这两个属性的 prop。它与 netxjs 完美配合react-router,也可能与 netxjs 配合良好Link。
<Link component={NextjsLink}>Link Text</Link>
Run Code Online (Sandbox Code Playgroud)
这里更改nextjs链接的导入名称。
您可以使用 Next.js 包装 Material-UI 链接。这将提供同时使用两者的好处。
import NextLink from 'next/link'
import { Link as MUILink } from '@material-ui/core';
// ...
<NextLink href="/" passHref>
<MUILink variant="body2">Your Link</MUILink>
</NextLink>
Run Code Online (Sandbox Code Playgroud)
为了避免参考警告和一些错误,我必须这样做。
import NextLink from 'next/link';
import { Link as MuiLink } from '@mui/material';
const Link = forwardRef((props: any, ref:any)=>{
const {href} = props;
return <NextLink href={href} passHref >
<MuiLink ref={ref} {...props}/>
</NextLink>
})
Link.displayName = 'CustomLink';
Run Code Online (Sandbox Code Playgroud)
我就是这样使用的。
<CardActionArea LinkComponent={Link} href={'/home'}>
...
</CardActionArea>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1063 次 |
| 最近记录: |