Javascript 如何在react js中从一个页面导航到另一个页面?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37295377/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:10:16  来源:igfitidea点击:

how to navigate from one page to another in react js?

javascriptreactjsreact-router

提问by user5711656

I have two components. In first component I have one button. On click of button I want to navigate to another component or another page.

我有两个组件。在第一个组件中,我有一个按钮。单击按钮时,我想导航到另一个组件或另一个页面。

here is my code http://codepen.io/naveennsit/pen/pymqPa?editors=1010

这是我的代码 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'))

回答by Bens Steves

There are two approaches here, both fairly easy.

这里有两种方法,都很容易。

Approach 1: Using React Router

方法一:使用 React Router

Make sure you have the route set up somewhere in your project already. It should contain this information at the very least: path and component. It should be defined something like this:

确保您已经在项目中的某处设置了路线。它至少应该包含以下信息:路径和组件。它应该像这样定义:

import YourComponent from "./path/of/your/component"; 

<Route path="/insert/your/path/here" component={YourComponent} /> 

Next, you want to update your handleClickfunction to use a Linkfrom react-router-dom(may have to install this package if you don't already have it using npm i react-router-dom).

接下来,您要更新您的handleClick函数以使用Linkfrom react-router-dom(如果您还没有使用,则可能必须安装此包npm i react-router-dom)。

Delete this (your handleClickfunction you don't need it with Link):

删除这个(你的handleClick函数不需要它Link):

handleClick(){
  alert('---');
}
    render() {
        return <button onClick={this.handleClick}>hello</button>
    }

}

Now change your render method to this:

现在将您的渲染方法更改为:

    render() {
        return (
          <div>
            <Link to="/insert/your/path/here" className="btn btn-primary">hello</Link>
         </div>
       ); 
    }

}

Give Linkthe same classNames that you would your button so it's styled as a button and not an anchor tag.

提供Link与您的按钮相同的 classNames,使其样式为按钮而不是锚标记。

Putting it all together.

把它放在一起。

//Wherever your router is with your routes

//无论你的路由器在哪里你的路由

    import YourComponent from "./path/of/your/component";

    <Router>
      <Route exact path="/insert/your/path/here" component={YourComponent} />
    </Router>

//The component that has the handleClick function

//具有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>
     );
  }
}

Approach 2: Using window.open

方法二:使用 window.open

Still make sure you have the route set up like above. The difference here is that you will not be using Linkwhich means you will need your handleClickfunction. That will be the only thing that changes.

仍然确保你有如上设置的路线。这里的区别在于您不会使用Link这意味着您将需要您的handleClick功能。那将是唯一改变的事情。

Change this:

改变这个:

handleClick(){
  alert('---');
}

to this:

对此:

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". 
}

That's it. If you want to make your paths dynamic, meaning they include variables like id's or names etc. See below.

就是这样。如果你想让你的路径动态化,这意味着它们包括诸如 id 或名称等变量。见下文。

Dynamic Paths

动态路径

Dynamic paths can include names and id's or whatever variable you would like. You first have to adjust your route and then change your Link or locations accordingly.

动态路径可以包括名称和 ID 或您想要的任何变量。您首先必须调整您的路线,然后相应地更改您的链接或位置。

Change the Route to this:

将路由更改为:

<Route path="/insert/your/path/here/:name" component={YourComponent} />

Notice the colon (:), this allows you to inject a string here via variable.

注意冒号 (:),这允许您通过变量在此处注入字符串。

Update your Link to this:

更新您的链接:

<Link to={`/insert/your/path/here/${variableName}`}>hello</Link>

And if you are using window.openupdate it like so:

如果你使用window.open更新它像这样:

window.open(`/insert/your/path/here/${variableName}`); 

A few things to point out here. You are using brackets after the equal sign because that tells React, hey I need to input a variable here. Next notice the back ticks ` this tells React that you are using a string literal which means hey I want you to interpret this as a string but first get the value of my variable in here and turn into a string for me. And the ${} allows you to place a variable so React can properly interpret it. So all together, react reads that line as: take the user to path "/insert/your/path/here/valueOfVariablName" then React checks the routes for that path and says hey we have something that is "/insert/your/path/here/:name" so :name must equal valueOfVariableName. Hope that makes a little sense. You can verify dynamic path's in your console. Log your props. You should see an object that contains location, history, etc.

这里有几点需要指出。你在等号后面使用括号,因为这告诉 React,嘿,我需要在这里输入一个变量。接下来注意反勾号 ` 这告诉 React 你正在使用一个字符串文字,这意味着嘿,我希望你将它解释为一个字符串,但首先在这里获取我的变量的值并为我转换为一个字符串。${} 允许您放置一个变量,以便 React 可以正确解释它。所以总的来说,react 读取该行为:将用户带到路径“/insert/your/path/here/valueOfVariablName”然后 React 检查该路径的路由并说嘿我们有一些东西是“/insert/your/path /here/:name" 所以 :name 必须等于 valueOfVariableName。希望这有点道理。您可以在控制台中验证动态路径。记录你的道具。

You can also read more about React-Router here. Raw link: https://medium.com/@pshrmn/a-simple-react-router-v4-tutorial-7f23ff27adf

您还可以在此处阅读有关 React-Router 的更多信息。原始链接:https: //medium.com/@pshrmn/a-simple-react-router-v4-tutorial-7f23ff27adf

If anyone has a better resource. Please feel free to edit my answer or leave a comment with it.

如果有人有更好的资源。请随时编辑我的答案或留下评论。

I hope this helps anyone who comes across this question. Btw you can pass state through the Linkas well. Please post another question if you would like to know how to do that.

我希望这可以帮助遇到这个问题的任何人。顺便说一句,您也可以通过状态传递Link。如果您想知道如何做到这一点,请发布另一个问题。

回答by Lars Graubner

If you want to build a single app I'd suggest using React Router. Otherwise you could just use plain Javascript:

如果你想构建一个单一的应用程序,我建议使用React Router。否则你可以只使用普通的 Javascript:

window.location = 'newUrl';

回答by sun1211

We shuold use struct like bellow

我们应该使用如下结构

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 >
    );
  }
}

with History.js is

与 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;

回答by Maheshvirus

Below are the best ways to deal with react navigations

以下是处理反应导航的最佳方法

Using useHistory()from react-router-dom

使用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;

Using Linkfrom react-router-dom

使用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;

Using Redirectfrom react-router

使用Redirect来自react-router

  import { Redirect } from 'react-router';

   <Redirect to='/componentURL' />

回答by Yilmaz

We use Link to navigate around to different routes that are hosted or being routed by react-router.

我们使用 Link 导航到由 react-router 托管或路由的不同路由。

class App extends React.Component {
    render(){
        return (
            <div>
                <BrowserRouter>
                    <div>
                    <Route path="/"  component={Landing} exact />
                    <Route path="/surveys" component={Dashboard}/>
                    </div>
                </BrowserRouter>

            </div>
        )
    }
}

for those two components above you can use Link.

对于上面的这两个组件,您可以使用 Link。

<Link to="/surveys">go to my surveys</Link>

However, anchor tags are used to navigate to completely different HTML documents. for example for google oauth, if you wanna log in the user, you have to navigate to a different url, when a user clicks on the "Login with Google" button.

但是,锚标记用于导航到完全不同的 HTML 文档。例如,对于 google oauth,如果您想登录用户,当用户单击“使用 Google 登录”按钮时,您必须导航到不同的 url。

<a href="/auth/google">Login with Google</a>