어떻게 반응 js에서 한 페이지에서 다른 페이지로 이동합니까?
컴포넌트는 2개입니다.첫 번째 컴포넌트에는 버튼이 하나 있습니다.버튼을 클릭하면 다른 컴포넌트 또는 다른 페이지로 이동합니다.
여기 제 코드가 있습니다.http://codepen.io/naveennsit/pen/pymqPa?editors=1010
class App extends React.Component {
handleClick(){
alert('---');
}
render() {
return <button onClick={this.handleClick}>hello</button>
}
}
class Second extends React.Component {
render() {
return <label>second component</label>
}
}
React.render( <App /> , document.getElementById('app'))
여기에는 두 가지 접근법이 있는데, 둘 다 상당히 쉽습니다.
접근법 1: 리액트라우터 사용
프로젝트 내 어딘가에 경로가 이미 설정되어 있는지 확인하십시오.이 정보에는 최소한 경로 및 구성 요소 정보가 포함되어 있어야 합니다.다음과 같이 정의해야 합니다.
import YourComponent from "./path/of/your/component";
<Route path="/insert/your/path/here" component={YourComponent} />
다음으로는 다음 정보를 갱신하고 싶다.handleClick사용하는 기능Link부터react-router-dom(이 패키지가 아직 설치되어 있지 않은 경우 이 패키지를 인스톨 할 필요가 있는 경우가 있습니다.npm i react-router-dom).
삭제(사용자 이름)handleClick불필요한 기능Link):
handleClick(){
alert('---');
}
render() {
return <button onClick={this.handleClick}>hello</button>
}
}
렌더링 방법을 다음과 같이 변경합니다.
render() {
return (
<div>
<Link to="/insert/your/path/here" className="btn btn-primary">hello</Link>
</div>
);
}
}
줘Link동일한 classNames 버튼을 사용하여 앵커 태그가 아닌 버튼으로 스타일링됩니다.
다 합쳐서.
//루트와 함께 라우터가 있는 곳
import YourComponent from "./path/of/your/component";
<Router>
<Route exact path="/insert/your/path/here" component={YourComponent} />
</Router>
//handle Click 기능이 있는 컴포넌트
import { Link } from "react-router-dom";
class App extends Component {
render() {
return(
<div>
<Link to="/insert/your/path/here" className="btn btn-primary">hello</Link>
</div>
);
}
}
접근법 2: 사용window.open
루트가 위와 같이 설정되어 있는 것을 확인해 주세요.여기서의 차이는, 이 기능을 사용하지 않는 것입니다.Link그 말은 즉, 당신은 그 정보가handleClick기능.그것만 바뀔 거야.
변경:
handleClick(){
alert('---');
}
다음과 같이 입력합니다.
handleClick(){
window.open("/insert/your/path/here");
//this opens in a new tab (believe that is what the owner of the question wanted if not you can do window.location.href = "/insert/your/path/here".
}
바로 그겁니다.경로를 동적으로 만들려면 ID나 이름 등의 변수를 포함합니다.이하를 참조해 주세요.
동적 경로
동적 경로에는 이름과 ID 또는 원하는 변수가 포함될 수 있습니다.먼저 경로를 조정하고 그에 따라 링크 또는 위치를 변경해야 합니다.
루트를 다음과 같이 변경합니다.
<Route path="/insert/your/path/here/:name" component={YourComponent} />
콜론(:)에 주의해 주세요.이것에 의해, 변수를 개입시켜 문자열을 삽입할 수 있습니다.
링크 업데이트:
<Link to={`/insert/your/path/here/${variableName}`}>hello</Link>
그리고 만약 당신이 그것을 사용하고 있다면window.open다음과 같이 업데이트합니다.
window.open(`/insert/your/path/here/${variableName}`);
여기서 몇 가지 짚고 넘어가야 할 것이 있습니다.등호 뒤에 대괄호를 사용하면 React에 "여기에 변수를 입력해야 합니다."라는 메시지가 표시되므로 대괄호를 사용합니다.다음 주의사항: " this is are you using string literal" (스트링 리터럴을 사용하고 있음을 React에게 알립니다.즉, 이 문자열은 문자열로 해석해 주셨으면 합니다만, 우선 여기서 변수 값을 가져와 문자열로 변환해 주셨으면 합니다.${}을(를) 사용하면 변수를 배치하여 React가 적절하게 해석할 수 있습니다.따라서 전체 react는 "/insert/your/path/here/valueOfVariableName" 경로로 사용자를 이동한 다음 해당 경로의 경로를 확인하고 "/insert/your/path/here/:name"이 있으므로 :name은 ValueOfVariableName과 같아야 합니다.그게 말이 됐으면 좋겠어요.콘솔에서 동적 경로를 확인할 수 있습니다.소품들을 통나무로 만들어라.위치, 이력 등을 포함한 오브젝트가 표시됩니다.
React-Router에 대한 자세한 내용은 여기를 참조하십시오.raw 링크: https://medium.com/@pshrmn/a-syslog-syslog-v4-syslog-7f23ff27adf
더 나은 자원을 가진 사람이 있다면요자유롭게 제 답변을 수정하거나 댓글을 달아주세요.
나는 이것이 이 질문을 접하는 모든 사람에게 도움이 되기를 바란다. 이 할 수 방법은 '나중에', '나중에', '나중에', '나중에', '나중에', '나중에', '나중에', '나중에', '나중에', '나중에', '나중에', '나중에', '나중에', '나중에', '나중에'를 통해서.Link뿐만 아니라.만 니, 어떻게 해야 할지 알고 싶다면 다른 질문을 해 주세요.그 방법을 알고 싶으시면 다른 질문을 올려주세요.
반응 탐색에 대처하는 가장 좋은 방법은 다음과 같습니다.
용 사?useHistory()부에서react-router-dom
import React from 'react';
import { useHistory } from "react-router-dom";
function NavigationDemo() {
const history = useHistory();
const navigateTo = () => history.push('/componentURL');//eg.history.push('/login');
return (
<div>
<button onClick={navigateTo} type="button" />
</div>
);
}
export default NavigationDemo;
용 사?Link부에서react-router-dom
import React from 'react';
import { Link } from "react-router-dom";
function NavigationDemo() {
return (
<div>
<Link to={{pathname: '/componentURL'}}>NavigateNow</Link>
</div>
);
}
export default NavigationDemo;
용 사?Redirect부에서react-router
import { Redirect } from 'react-router';
<Redirect to='/componentURL' />
갱신된 답변:
"flash-dom" : "^6.2",
이제 useHistory() 대신 useNavigate()를 'react-router-dom'에서 내보내 이러한 모든 탐색을 처리합니다.
import { useNavigate } from "react-router-dom"
리다이렉트 방법:
const navigate = useNavigate()
const onClickHandler = () => navigate(`/product/123`)
단일 앱을 만들고 싶다면 리액트 라우터를 사용하는 것이 좋습니다.그렇지 않으면 플레인 Javascript를 사용할 수 있습니다.
window.location = 'newUrl';
우리는 벨로우와 같은 구조를 사용한다.
import history from 'services/History'
import { Router , Route, Switch } from "react-router-dom";
class App extends Component {
render() {
return (
<Router history={history} >
<div className="root">
<Switch>
<Route path="/" component={MainPage} exact />
<Route path="/dashboard" component={DashBoard} exact />
<Route path="/docs" component={Docs} exact />
<Route component={ErrorPage} />
</Switch>
</div>
</Router >
);
}
}
history.js는
// google analytics
import ReactGA from 'react-ga';
import createHistory from 'history/createBrowserHistory';
ReactGA.initialize('UA-156453259-1');
ReactGA.pageview(window.location.pathname);
const history = createHistory();
history.listen((location) => {
ReactGA.set({
page: location.pathname,
});
ReactGA.pageview(location.pathname);
});
export default history;
링크를 사용하여 리액트라우터에 의해 호스트되거나 라우팅되는 다양한 루트로 이동합니다.
class App extends React.Component {
render(){
return (
<div>
<BrowserRouter>
<div>
<Route path="/" component={Landing} exact />
<Route path="/surveys" component={Dashboard}/>
</div>
</BrowserRouter>
</div>
)
}
}
위의 2개의 컴포넌트에 대해서는 링크를 사용할 수 있습니다.
<Link to="/surveys">go to my surveys</Link>
그러나 앵커 태그는 완전히 다른 HTML 문서로 이동하기 위해 사용됩니다.예를 들어 Google oauth의 경우 사용자가 "Google 로그인" 버튼을 클릭할 때 다른 URL로 이동해야 합니다.
<a href="/auth/google">Login with Google</a>
언급URL : https://stackoverflow.com/questions/37295377/how-to-navigate-from-one-page-to-another-in-react-js
'programing' 카테고리의 다른 글
| spring-boot 어플리케이션에서 swag-ui를 기동할 수 없습니다. (0) | 2023.04.04 |
|---|---|
| 일반 클래스의 형식 매개 변수에서 새 개체 만들기 (0) | 2023.04.04 |
| 페이지로 Visual Composer 단축 코드 렌더링 (0) | 2023.04.04 |
| 각도 포함 JSDocJS (0) | 2023.04.04 |
| WooCommerce 계정 등록 메일에서 사용자 이름에 액세스합니다(독일어로 WooCommerce를 통한 DOI). (0) | 2023.04.04 |