如何使 Material UI react按钮充当 react-router-dom 链接?

IT技术 javascript reactjs react-router material-ui react-router-dom
2021-04-26 06:45:56

如何使Material UIreactButton组件充当react-router-dom 中Link组件而不会失去其原始样式?就像点击改变路线一样。

import Button from '@material-ui/core/Button';

<Button variant="contained" color="primary">
    About Page
</Button>

像这样,但保持原来的Button风格:

import Button from '@material-ui/core/Button';
import { Link } from 'react-router-dom';

<Button variant="contained" color="primary">
    <Link to="/about">
        About Page
    </Link>
</Button>
3个回答

好的,这很容易,我不知道为什么它不适合我:

只需这样做:

import Button from '@material-ui/core/Button';
import { Link } from 'react-router-dom';

<Button component={Link} to="/about" variant="contained" color="primary">
  About Page
</Button>

您可以在https://next.material-ui.com/guides/routing/找到更多详细信息

您需要<Button /><Link />组件包裹在内部

import Button from '@material-ui/core/Button';
import { Link } from 'react-router-dom';

const ButtonWithLink = () => (
  <Link to="/about">
   <Button variant="contained" color="primary">
     About Page
   </Button>
  </Link>
)

MUI 5 进一步简化了这一点。只需提供一个Button带有href属性的 MUI 如下所示:

import Button from '@mui/material/Button';


<Button href="/" variant="contained">
  Link
</Button>