简体   繁体   English

React Material UI + React Router >>>> 我不能在按钮的 onClick 函数中使用 Redirect

[英]React Material UI + React Router >>>> I cannot use Redirect inside a onClick function in a button

I am trying to trigger the Redirect React Dom that is my button component in the handleMenuItemClick() function.我正在尝试在handleMenuItemClick()函数中触发 Redirect React Dom,它是我的按钮组件。 But nothing happens.但什么也没有发生。 I have tried a bunch of stuff but but still no success.我尝试了很多东西,但仍然没有成功。

How can I make the both work together?我怎样才能让两者一起工作? My best try was to make a function that return the Redirect component as I saw in one post around, but still no success.我最好的尝试是创建一个函数来返回重定向组件,正如我在一篇文章中看到的那样,但仍然没有成功。 My Code:我的代码:

import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import { Grid, Button, ButtonGroup, ArrowDropDownIcon, ClickAwayListener, Grow, Paper, Popper, MenuItem, MenuList, Link }  from '@material-ui/core/Grid';


const SplitButton = (props) => {
    const [open, setOpen] = React.useState(false);
    const anchorRef = React.useRef(null);
    const [selectedIndex, setSelectedIndex] = React.useState(1);

    const myGroups = props.myGroups


    const handleMenuItemClick = (event, index) => {
        setSelectedIndex(index);
        setOpen(false);
        return <Redirect to={`/groups/${index}`} />
    };

    const handleToggle = () => {
        setOpen((prevOpen) => !prevOpen);
    };


    const handleClose = (event) => {
        if (anchorRef.current && anchorRef.current.contains(event.target)) {
            return;
        }

        setOpen(false);
    };




    return (
        <>
            <ButtonGroup variant="contained" color="primary" ref={anchorRef} aria-label="split button">
                <Button onClick={null}>My Groups</Button>
                <Button
                    color="primary"
                    size="small"
                    aria-controls={open ? 'split-button-menu' : undefined}
                    aria-expanded={open ? 'true' : undefined}
                    aria-label="select merge strategy"
                    aria-haspopup="menu"
                    onClick={handleToggle}
                >
                    <ArrowDropDownIcon />
                </Button>
            </ButtonGroup>
            <Popper open={open} anchorEl={anchorRef.current} role={undefined} transition disablePortal>
                {({ TransitionProps, placement }) => (
                    <Grow
                        {...TransitionProps}
                        style={{
                            transformOrigin: placement === 'bottom' ? 'center top' : 'center bottom',
                        }}
                    >
                        <Paper>
                            <ClickAwayListener onClickAway={handleClose}>
                                <MenuList id="split-button-menu">
                                    { myGroups.map((group) => (
                                        <MenuItem
                                            key={group.id}
                                            onClick={(event) => handleMenuItemClick(event, group.id)}
                                        >
                                            {group.title}
                                        </MenuItem>
                                    ))}
                                </MenuList>
                            </ClickAwayListener>
                        </Paper>
                    </Grow>
                )}
            </Popper>
        </>
    );
}

export default SplitButton

You can redirect user via 2 methods: useHistory or <Redirect />您可以通过两种方法重定向用户: useHistory<Redirect />

useHistory hook使用历史挂钩

If you want to redirect the user directly on click, you can treat the code imperatively and tell React what to do:如果你想给用户直接点击重定向,你可以把势在必行的代码,并告诉反应怎么

const history = useHistory();
    
const handleMenuItemClick = (event, index) => {
    setSelectedIndex(index);
    setOpen(false);
    history.push(`/groups/${index}`)
};
    

More info https://reactrouter.com/web/api/Hooks/usehistory更多信息https://reactrouter.com/web/api/Hooks/usehistory

Redirect component重定向组件

Or if you feel more comfortable using React's default declarative model, you can say what's changed and allow your code to react to this change:或者,如果您觉得使用 React 的默认声明式模型更舒服,您可以说出更改的内容并让您的代码对这种更改做出反应

const [redirectUrl, setRedirectUrl] = useState('')
    
const handleMenuItemClick = (event, index) => {
    setSelectedIndex(index);
    setOpen(false);
    setRedirectUrl(`/groups/${index}`)
};

if (redirectUrl) {
    return <Redirect to={redirectUrl} />
}

return (
    <>
        <ButtonGroup variant="contained" color="primary" ref={anchorRef} aria-label="split button">
            <Button onClick={null}>My Groups</Button>
            <Button

...

More info https://reactrouter.com/web/api/Redirect更多信息https://reactrouter.com/web/api/Redirect

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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