
[英]Can you use Material-UI Link with react-router-dom Link?
[英]Link in Material UI and React Router Dom
它需要看起来像 Material-UI 中的<Link
> 但问题是它在导航时进行刷新。 所以我所做的是使用 react-router-dom 的<Link>
Link> 并将 Material-UI 的<Link>
作为其组件。
问题出在 UI 上,我想遵循 MUI Link 的 UI,而不是 react-router-dom。 在不修改其 CSS 的大部分内容的情况下,是否有更短的方法?
import { Link as LinkBase } from '@mui/material';
import { Link } from 'react-router-dom';
<Link
component={LinkBase}
to={`/products/${id}`}
>
{name}
</Link>
您可以在 @mui/material 的 components 属性中传递 react-router-dom 的链接
import './App.css';
import { Link as LinkBase } from '@mui/material';
import { Link, BrowserRouter, Routes, Route } from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<Routes>
<Route
path="/"
element={
<LinkBase component={Link} to="/home">
home
</LinkBase>
}
/>
<Route path="/home" element={<h1>a</h1>} />
</Routes>
</BrowserRouter>
);
}
export default App;
首先。 我认为您需要阅读MUI 指南,其中包含 react-router 的示例。
@Alexsander Gutierreez 的回答绝对正确。 但是,如果您想更改所有 MUI 的默认行为(包含链接等...),您可以:
import RouterLink, {Props as RouterLinkProps} from "@docusaurus/Link";
import {createTheme, LinkProps, ThemeProvider as MuiThemeProvider} from "@mui/material";
const LinkBehavior = React.forwardRef<
HTMLAnchorElement,
Omit<RouterLinkProps, "to"> & { href: RouterLinkProps["to"] }
>((props, ref) => {
const {href, ...other} = props;
return <RouterLink ref={ref} to={href} {...other} />;
});
function App() {
const theme = createTheme({
components: {
MuiLink: {
defaultProps: {
component: LinkBehavior,
} as LinkProps,
},
MuiButtonBase: {
defaultProps: {
LinkComponent: LinkBehavior,
},
},
MuiListItemButton: {
defaultProps: {
LinkComponent: LinkBehavior,
},
},
MuiIconButton: {
defaultProps: {
LinkComponent: LinkBehavior,
},
},
},
});
return (
<MuiThemeProvider theme={theme}>
<SomeChildren/>
</MuiThemeProvider>
);
}
现在您将能够在<MuiThemeProvider/>
中使用 MUI 的<Link/>
作为 react-router-dom 的<Link/>
> 。
import {Link} from '@mui/material';
// in <MuiThemeProvider/>
function SomeChildren() {
return (
<BrowserRouter>
<Routes>
<Route
path="/"
element={
<Link to="/home">home</Link>
}
/>
<Route path="/home" element={<h1>a</h1>} />
</Routes>
</BrowserRouter>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.