source

리액트 라우터 v4에서 액티브 링크를 스타일링하려면 어떻게 해야 합니까?

myloves 2023. 3. 4. 15:25

리액트 라우터 v4에서 액티브 링크를 스타일링하려면 어떻게 해야 합니까?

react-router v3에서는 activeStyle과 activeClassName을 사용하여 active Link를 스타일링했습니다.

우리는 이런 일을 할 수 있다.

  <div id="tags-container">
    {tags.map(t =>
      <Link
        className="tags"
        activeStyle={{ color: 'red' }}
        to={t.path}
      >
        {t.title}
      </Link>
    )}
  </div>

v4에서도 어떻게 같은 일을 할 수 있는지 알고 싶어요.

링크 대신 NavLink를 사용합니다.문서화된 것은 아니지만 예상대로 작동합니다.https://github.com/ReactTraining/react-router/issues/4318

업데이트 17.05.2017:

https://reacttraining.com/react-router/web/api/NavLink

다음과 같이 할 수 있습니다.NavLinkreact-routerv4

 <div id="tags-container">
   {tags.map(t =>
     <NavLink
       className="tags"
       activeStyle={{ color: 'red' }}
       to={t.path}
     >
       {t.title}
     </NavLink>
   )}
 </div>

링크를 클릭해도 올바르게 업데이트되지 않고 경로가 변경되지만 F5 키를 누르면 정상적으로 작동하는 경우를 제외하고 탐색 메뉴가 작동하는 문제가 발생하는 경우 다음과 같이 하십시오.

이는 아마도 Redux를 사용하고 있기 때문에 발생합니다.shouldComponentUpdate라이프 사이클 방법connect기능.Nav 컴포넌트가 포장되어 있을 것입니다.connect다 좋습니다. shouldComponentUpdate네 인생을 망치고 있는 거야

수정하려면 , 라우터를 사용하고 있는 에 접속해 주세요.mapStateToProps기능:

// This lets shouldComponentUpdate know that the route changed,
// which allows the Nav to re-render properly when the route changes, woot!
const mapStateToProps = (state) => {
  return {
    router: state.router,
  }
}

// or, if you prefer pro style destructure shorthand:
const mapStateToProps = ({ router }) => ({ router })

어디인지 잘 모르겠다면state.routerreducer를 조합한 파일에서 얻을 수 있습니다.이 파일은 다음과 같습니다.

import { combineReducers } from 'redux'
import { routerReducer } from 'react-router-redux'
import authReducer from './components/auth/auth_reducer'

export default combineReducers({
  router: routerReducer,
  auth: authReducer,
})

여기 예쁜 발레러 Nav Link를 위한 HTML과 CSS가 있습니다.

HTML

<ul id="Nav_menu">
  <li>
    <NavLink
      to="/home"
      className="Nav_link"
      activeClassName="activeRoute"
      activeStyle={{ color: 'teal' }}
    >
      HOME
    </NavLink>
  </li>
  <li>
    <NavLink
    to="/products"
    className="Nav_link"
    activeClassName="activeRoute"
    activeStyle={{ color: 'teal' }}
    >
      PRODUCTS
    </NavLink>
  </li>
</ul>

주의: 링크하는 경우"/",놓다exactNavLink에 있습니다.

CSS

#Nav_menu {
  display: flex;
  flex-direction: row;
  width: 100%;
  height: 100%;
  list-style-type: none;
  margin: 0;
  padding: 0;
}

.Nav_link:link {
  color: #fff;
  font-size: 1.6rem;
  line-height: 1.6rem;
  text-decoration: none;
}
.Nav_link:visited {
  color: #fff;
}
.Nav_link:hover {
  color: yellow;
}
.Nav_link:active {
  color: teal;
}

.activeRoute {
  background-color: yellow;
  border-bottom: 0.4rem solid teal;
  cursor: not-allowed;
}

공지activeStyleHTML 마크업으로 지정합니다.이것이 액티브 루트/링크에서 텍스트 색상을 변경할 수 있는 유일한 방법입니다.제가 이걸 넣었을 때 효과가 없었어요.color: teal;에서activeRouteCSS 클래스https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/docs/api/NavLink.md의 다른 탭에서 엽니다.

내가 왜 그랬는지 모르겠다면rem대신px이는 웹 접근성과 기반을 조사할 수 있는 절호의 기회입니다.font-size: 10px;.

몸매 잘 챙기고 재밌게 놀아요.

리액트 라우터 v6:

출처: React Router를 사용한 Active NavLink 클래스

이게 v4에 대한 질문이었다는 건 알지만, v6가 출시됐기 때문에 이 문제는className현재 함수를 받아들여 통과시키는 특성isActive다음과 같은 부울 속성:

<NavLink
  to="users"
  className={({ isActive }) => (isActive ? 'active' : 'inactive')}
>
  Users
</NavLink>

v6이 출시되었기 때문에 여러 클래스를 추가할 수도 있습니다.

<NavLink
  to="users"
  className={({ isActive }) =>
    isActive ? 'bg-green-500 font-bold' : 'bg-red-500 font-thin'
  }
>
  Users
</NavLink>

데모: 리액트 라우터를 사용한 액티브 NavLink 클래스

모든 것이 여전히 동일하게 작동합니다.단, react-router-dom v4 치환Link와 함께NavLink

import { NavLink as Link } from 'react-router-dom';괜찮네요.주의: 기본적으로 네비게이션 링크는 활성화되어 있으므로 스타일을 지정할 수 있습니다.a:active or 또는activeStyle={{color: 'red'}}

@agm1984의 답변에 대해 자세히 설명하겠습니다.NavLinks의 솔루션은 스타일을 올바르게 업데이트하지 않는 것입니다.routerReducer부에서react-router-redux, 날 위해 일하지 않았습니다.는 나에게 효과가 없었다.대신 문제가 된은 '아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아.connect는 「」를 사용합니다.shouldComponentUpdateNavLinks는 NavLinks를 사용합니다.

은 옵션 object를 options object를 options abject로 이었다.connect 변수로서 다음과합니다.

export default connect(mapStateToProps, null, null, { pure: false })(NavItems);

react-router v4 커스텀링크 문서의 다음 예를 참조해 주십시오.

const OldSchoolMenuLink = ({ label, to, activeOnlyWhenExact }) => (
  <Route path={to} exact={activeOnlyWhenExact} children={({ match }) => (
    <div className={match ? 'active' : ''}>
      {match ? '> ' : ''}<Link to={to}>{label}</Link>
    </div>
  )}/>
);

이 경우 다음 컴포넌트를 생성할 수 있습니다.

const CustomLink = ({ activeStyle, children, className, to, activeOnlyWhenExact }) => (
  <Route path={to} exact={activeOnlyWhenExact} children={({ match }) => (
    <Link to={to} className={className} style={match && activeStyle}>{children}</Link>
  )}/>
);

다음으로 다음과 같이 사용합니다.

  <div id="tags-container">
    {tags.map(t =>
      <CustomLink
        className="tags"
        activeStyle={{ color: 'red' }}
        to={t.path}
      >
        {t.title}
      </CustomLink>
    )}
  </div>

언급URL : https://stackoverflow.com/questions/42044214/how-can-i-style-active-link-in-react-router-v4