programing

경로를 사용하는 재료 UI 메뉴

codeshow 2023. 3. 28. 22:23
반응형

경로를 사용하는 재료 UI 메뉴

재료의 장난을 치고 있다루트를 사용하여 Left Nav를 구현했지만 Icon Menu 또는 링크 또는 루트로 작업하는 메뉴를 얻을 수 있는 방법을 찾을 수 없었습니다.좋은 소스나 튜토리얼을 가르쳐 주실 분?설명서가 부족하며, 두 구성 요소 모두 LeftNav와 달리 'menuItems'를 속성으로 지원하지 않는 것 같습니다.

또 다른 오래된 업데이트:

containerElement소품은 더 이상 지원되지 않습니다.component대신 소품입니다.

문서를 확인하십시오.


2016년 12월 편집: thelinkButtonprop가 권장되지 않습니다.경고 메시지가 표시됩니다.

Warning: Unknown props `linkButton` on <a> tag.

프로펠러를 분리하기만 하면 됩니다.

<MenuItem
  containerElement={<Link to="/profile" />}
  primaryText="Profile"
  leftIcon={
    <FontIcon className="material-icons">people</FontIcon>
  }
/>

다음은 보고서 예시라이브 데모보여드리겠습니다.


원답:

리액트 라우터를 사용하고 있다면<Link to="/some/page" />그보다는<a>태그를 붙입니다.

이를 위해서는 다음 명령어를 사용해야 합니다.containerElement받침대

<MenuItem
  linkButton
  containerElement={<Link to="/profile" />}
  primaryText="Profile"
  leftIcon={
    <FontIcon className="material-icons">people</FontIcon>
  }
/>

(the)={true}합격만 하면 생략할 수 있다true바꿔 말하면,<MenuItem linkButton />와 같다<MenuItem linkButton={true} />)

containerElement그리고.linkButton소품들은 실제로 버튼 섹션에 문서화되어 있지만, 당신은 그것을 사용할 수 있습니다.MenuItem뿐만 아니라.

Material-UI 1.0 이후 새로운 구문은 다음과 같습니다.

<MenuItem
  component={Link}
  // the 'to' prop (and any other props not recognized by MenuItem itself)
  // will be passed down to the Link component
  to="/profile"
>
  Profile
</MenuItem>

(주의: 이 예에는 아이콘이 포함되어 있지 않습니다.새로운 것이 있다ListItemIcon컴포넌트).

를 설정할 수 있습니다.linkButtton을 떠받치다.MenuItem링크를 생성하고 다음 링크를 추가합니다.href.

<MenuItem linkButton={true} href="link/to/some/page" primaryText="Sample Link" />

react 16.4.2 및 react-router 4.2.2에서는(2018년 9월) 기존 답변 중 어느 것도 작동하지 않았기 때문에 다음과 같은 솔루션을 사용할 수 있었습니다.

<Link to='/notifications' style={{ textDecoration: 'none' }}>
   <MenuItem>Notifications</MenuItem>
</Link>

보시는 바와 같이 MenuItem 컴포넌트는 Link 컴포넌트로 둘러싸여 있으며 스타일을 추가했습니다.textDecoration: 'none'항목에 밑줄을 그지 않도록 합니다.

2020년 9월 현재, 작동되고 매우 간단한 것은

<MenuItem component="a" href="/your-path">Click Me</MenuItem>

보너스: 배지와 함께 아이콘을 추가하려면:

<MenuItem component="a" href="/your-path">
        <IconButton color="inherit" href="/your-path">
              <Badge badgeContent="12" color="secondary">
                <StarsSharpIcon color="action"/>
              </Badge>
        </IconButton>
Click Me
</MenuItem>

소품linkButtonEnhancedButton는 권장되지 않습니다.Link Button은 더 이상 필요하지 않습니다.href속성이 제공됩니다.v0.16.0에서는 삭제됩니다.

<MenuItem onTouchTap={this.handleClose} href="/link/data">Link Item</MenuItem>

정상적으로 동작합니다.

M-UI 4.x 를 사용하면,component을 떠받치다.MenuItem그리고 뭐 그런 거에 대해서

<MenuItem component='a' href='link/to/some/page'>Sample Link</MenuItem>

스스로 조금 검색한 후 조금 다른 솔루션을 선택하였습니다.

<MenuItem onClick={() => {handleClose("/#about")}}>About me</MenuItem>

지원되는 JS 함수:

function handleClose(nav) {
    window.location.href = nav;
}

다른 대안으로 사용할 수 있다는 걸 증명해 보이길 바라.

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


<MenuItem component={Link} to='/login'>
       Login
</MenuItem>

2021년 9월에 리액트 라우터와 MenuItem의 Link Propoid를 사용하여 작업을 수행했습니다.

v5에서는 이 기능이 유효했습니다.

외부 링크용

<MenuItem
    component={"a"}
    href={"https://example.com"}
>Go here</MenuItem>

또는 내부 링크

import { MenuItem } from "@mui/material";
import { Link } from "react-router-dom";
<MenuItem
    component={Link}
    to={"/users/2323"}
>Go here</MenuItem>

OnTouchTap이 작동하지 않습니다. OnTouchTap을 사용해야 합니다.아래 예를 참조하십시오.

  <MenuItem 
    onClick={this.logout}
    containerElement={<Link to="/" />}
    primaryText="Sign out"
    rightIcon={
      <b style={style.rightIcon}>
        <img
          className="menu-img"
          src="img/app/logout.png"
          alt="logout"
        />
      </b>
    }
  />

이것이 다른 사람들에게도 도움이 되기를 바란다

react-route-dom 및 MenuItem onClick 속성을 먼저 import react-router-dom을 사용할 수 있습니다. import { useHistory } from 'react-router-dom' 그런 다음 컴포넌트 내에서 onClick을 처리하는 함수를 선언합니다. const navigate = () => history.push('route/to/navigate') [ ]음 [MenuItem을 합니다. <MenuItem onClick={navigate}>Navigate</MenuItem>

v5.2.2부터는 다음을 사용할 수 있습니다.

import { MenuItem } from '@mui/material';
import { Link } from 'react-router-dom';

<MenuItem component={Link} to="/profile">
  Profile
</MenuItem>

요.<Link><MenuItem> 부착

오류:

     <MenuItem>
        <ListItemText>
            <Link to='/ticket-blotter' style={{ textDecoration: 'none' }}>
                TICKET BLOTTER 
            </Link>
        </ListItemText>
     </MenuItem>
       

솔루션:

        <Link to='/ticket-blotter' style={{ textDecoration: 'none' }}>
            <MenuItem>
                <ListItemText>
                    TICKET BLOTTER
                </ListItemText>
            </MenuItem>
        </Link>

가 못 containerElement에서 react-router 쓰고 0.17.2 및 ★★★★ UI ★react-router@v3그리고 여기 제게 효과가 있었던 작업이 있습니다.

  <MenuItem
    onTouchTap={() => {
      this._yourMethod()
      browserHistory.push('/howItWorks')
    }}
    primaryText="Menu Link"
  />

재료의사용할 수 있는 컴포넌트는 다음과 같습니다.AppBar,Drawer ★★★★★★★★★★★★★★★★★」ListItem . 。SelectableList라고 할 수 있다let SelectableList = MakeSelectable(List).

<div>
  <AppBar 
    onLeftIconButtonTouchTap={this.handleLeftIconButtonTouchTap}
    title={title}
    showMenuIconButton={true}
    zDepth={0}
  />
    <Drawer 
      open={this.state.open} 
      docked={true} 
      onRequestChange={(open, reason) => {
        this.setState({open:false})
      }}
    >
      <AppBar title={title} />
      <SelectableList
        value={location.pathname}
        onChange={this.handleRequestChangeList}
       >
        <Subheader>Selectable Contacts</Subheader>
        <ListItem
          value={"link1"}
          primaryText="Link1"
        />
        <ListItem
          value={"link2"}
          primaryText="Link2"
        />
      </SelectableList>
    </Drawer>
 </div>

이렇게 하면 나는 잘 된다.

import { useHistory } from 'react-router-dom';

const YourComponentName = () =>{
  
    const history = useHistory();
    const handleRoutes = (path) =>{
       history.push(path)
    }
    
  return(
    <>
      ...
      <MenuItem onClick={()=>handleRoutes('/dashboard')}>Dashboard</MenuItem>
      <MenuItem onClick={()=>handleRoutes('/profile')}>Profile</MenuItem>
      ...
    </>
)
}

2023년 답변:

import {Menu, MenuItem, Link} from '@mui/material'

<Menu>
  <MenuItem component={Link} href='/'>Home</MenuItem>
  <MenuItem component={Link} href='/settings/user'>My Settings</MenuItem>
<Menu />

2023년의 집필 시점에서는, 상기의 회답의 상당수는, MUI v5.11.6 를 사용해 테스트되고 있습니다.

인 a.Linkcomponent의 prop의 MenuItem는 , 을 합니다.Link MenuItem에서 할 수 Link요소는 여기에서 찾을 수 있습니다.

언급URL : https://stackoverflow.com/questions/32106513/material-ui-menu-using-routes

반응형