반응형
라우터 4 응답.활성 경로 가져오기
나는 코드를 가지고 있다.
라우터.js
import React from 'react';
import {render} from "react-dom";
import history from './history';
import {Router, Route} from 'react-router'
import Main from "./main/component";
import Profile from "./profile/component";
import TextStatus from "./textstatus/component";
import ContactList from "./contactlist/component";
render((
<Router history={history}>
<Main>
<Route
path="/:user_name"
component={Profile}
component_id="Profile"
/>
<Route
path="/:user_name/status"
component={TextStatus}
component_id="TextStatus"
/>
<Route
path="/:user_name/contacts"
component={ContactList}
component_id="ContactList"
/>
</Main>
</Router>
), document.getElementById("main"));
history.js
import createBrowserHistory from 'history/createBrowserHistory'
const history = createBrowserHistory();
export default history;
main/component.js //main 레이아웃
import React from 'react';
class Main extends React.Component {
render() {
return (this.props.children)
}
}
Main 구성 요소에서 현재 경로(component_id)를 얻는 방법은?
반응 라우터 1.0.3에서 나는 이렇게 했다.this.props.children.props.route.component_id
관심을 가져줘서 고마워!
v16.8+ 반응 및 라우터 v5+ 반응에 대한 업데이트:
사용하다useLocation
낚싯바늘을 달다
import { useLocation } from 'react-router-dom';
const Main = ({ children }) => {
const location = useLocation();
console.log(location.pathname); // outputs currently active route
return children;
};
export default Main;
구성 요소 포장withRouter
그리고 나서 당신은 다음 방법으로 현재의 활성 루트에 접속할 수 있다.this.props.location.pathname
.
예:
import React from 'react';
class Main extends React.Component {
render() {
console.log(this.props.location.pathname); // outputs currently active route
return (this.props.children)
}
}
export default withRouter(Main);
기본 구성요소를 순서대로 정렬하여 컨텍스트에서 위치 소품을 가져올 수 있다.
참조URL: https://stackoverflow.com/questions/48210703/react-router-4-get-active-route
반응형
'programing' 카테고리의 다른 글
마우스오버 시 클래스를 동적으로 추가 및 제거 - Vue.js (0) | 2022.03.24 |
---|---|
대응: 하위 도메인으로 리디렉션할 때 쿠키 보존 (0) | 2022.03.24 |
이 코드 조각에서 (이것은) 어떤 의미인가? (0) | 2022.03.24 |
조건부로 입력 비활성화(Vue.js) (0) | 2022.03.24 |
Vuetify - 배경색 설정 방법 (0) | 2022.03.24 |