我有两个组件。在第一个组件中,我有一个按钮。单击按钮后,我想导航到另一个组件或另一个页面。
这是我的代码 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:使用React Router
确保您已在项目中的某个位置设置了路线。它至少应该包含以下信息:路径和组件。它应该这样定义:
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
提供与按钮相同的类名,以便将其样式设置为按钮而不是锚标记。
将它们放在一起。
//无论你的路由器在哪里
import YourComponent from "./path/of/your/component";
<Router>
<Route exact path="/insert/your/path/here" component={YourComponent} />
</Router>
//具有handleClick功能的组件
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,嘿,我需要在这里输入一个变量。接下来注意后面的勾号`,这告诉React您正在使用字符串文字,这意味着嘿,我希望您将其解释为字符串,但首先在这里获取我的变量的值,然后将其转换为字符串。 ${} 允许您放置一个变量,以便 React 可以正确解释它。因此,React 将该行读取为:将用户带到路径“/insert/your/path/here/valueOfVariablName”,然后 React 检查该路径的路由并说嘿,我们有一些“/insert/your/path” /here/:name" 因此 :name 必须等于 valueOfVariableName。希望这有点道理。您可以在控制台中验证动态路径。记录你的道具。您应该看到一个包含位置、历史记录等的对象。
您还可以在这里阅读有关 React-Router 的更多信息。原始链接:https://medium.com/@pshrmn/a-simple-react-router-v4-tutorial-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' />
更新:在react-router-dom v6中,useHistory()被useNavigate()取代。示例:
import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();
navigate('/home');
更新答案:
“react-router-dom”:“^6.2.2”,
现在useNavigate() 不再是 useHistory(),而是从“react-router-dom”导出来处理所有此类导航。
import { useNavigate } from "react-router-dom"
重定向:
const navigate = useNavigate()
const onClickHandler = () => navigate(`/product/123`)
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>
)
}
}
对于上面这两个组件,您可以使用链接。
<Link to="/surveys">go to my surveys</Link>
但是,锚标记用于导航到完全不同的 HTML 文档。例如,对于 google oauth,如果您想登录用户,则当用户单击“使用 Google 登录”按钮时,您必须导航到不同的 url。
<a href="/auth/google">Login with Google</a>