如何在React JS中从一页导航到另一页? [英] how to navigate from one page to another in react js?

查看:74
本文介绍了如何在React JS中从一页导航到另一页?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个组成部分.在第一个组件中,我有一个按钮.单击按钮后,我想导航到另一个组件或另一个页面.

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.

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

推荐答案

这里有两种方法,都相当简单.

There are two approaches here, both fairly easy.

方法1:使用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} /> 

接下来,您想更新您的 handleClick 函数,以使用 react-router-dom 中的 Link (可能必须安装此软件包)如果您还没有使用 npm我有react-router-dom ).

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

删除此(您不需要使用 Link handleClick 函数):

Delete this (your handleClick function you don't need it with 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>
       ); 
    }

}

赋予 Link 与您的按钮相同的类名,以便将其样式设置为按钮而不是锚标记.

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

将所有内容放在一起.

//无论您的路由器与路线在何处

//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>

//具有handleClick功能的组件

//The component that has the handleClick function

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

Approach 2: Using window.open

仍然请确保您已经按照上述步骤设置了路线.此处的区别在于您将不会使用 Link ,这意味着您将需要 handleClick 函数.这将是唯一改变的事情.

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

更改此内容:

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或name等变量.请参见下文.

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

将路线更改为此:

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

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

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

将您的链接更新为此:

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

如果您使用的是 window.open ,请像这样更新它:

And if you are using window.open update it like so:

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

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

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.

您还可以在此处.原始链接: https://medium.com/@pshrmn/一个简单的反应路由器v4-教程7f23ff27adf

You can also read more about React-Router here. Raw link: 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.

我希望这会对遇到此问题的任何人有所帮助.顺便说一句,您也可以通过 Link 传递状态.如果您想知道该怎么做,请发表另一个问题.

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

这篇关于如何在React JS中从一页导航到另一页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆