简体   繁体   中英

React. Link MUI without reloading page

Using component MUI Link, my page is reloaded. So I use the Link component from react-route-dom, but it turns out that <.a> is inside another and error on console在此处输入图像描述

If I remove MUI.Link, then navbar looks like bad

Code:

import {Link as LinkRouter} from "react-router-dom"
import Link from "@mui/material/Link";

export default function Navbar() {
    return (
        <>
            <GlobalStyles styles={{ul: {margin: 0, padding: 0, listStyle: 'none'}}}/>
            <AppBar
                position="sticky"
                color="default"
                elevation={0}
                sx={{borderBottom: (theme) => `1px solid ${theme.palette.divider}`}}
            >
                <Toolbar sx={{flexWrap: 'wrap'}}>
                    <Typography variant="h4" color="inherit" noWrap sx={{flexGrow: 1}}>
                        <LinkRouter to="/account/wall" className="site-title">YourQuestion</LinkRouter>
                    </Typography>
                    <nav>
                        <CustomLink to="/account/wall">Wall</CustomLink>
                        <CustomLink to="/account/message">Message</CustomLink>
                        <CustomLink to="/account/notice">Notice</CustomLink>
                        <CustomLink to="/account/friends">Friends</CustomLink>
                        <CustomLink to="/account/profile">Profile</CustomLink>
                    </nav>
                </Toolbar>
            </AppBar>
        </>
    )
}

function CustomLink({to, children, ...props}) {
    return (
        <>
            <Link
                variant="button"
                color="text.primary"
                sx={{ my: 1, mx: 1.5 }}
            >
                <LinkRouter to={to} {...props}>
                    {children}
                </LinkRouter>
            </Link>
        </>
    )
}

My githubrepository

You can pass component="span" prop to MUI Link component like this:

<Link
    component="span"
    variant="button"
    color="text.primary"
    href="#"
    sx={{ my: 1, mx: 1.5 }}
>
    <LinkRouter to={to} {...props}>
      {children}
    </LinkRouter>
</Link>

You can use onClick props

      <Link
        sx={{ color: 'primary.main', cursor: 'pointer' }}
        onClick={() => navigate(ROUTES.login)}
        href="#"
      >
        Sign In
      </Link>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM