更改组件React Web

时间:2019-09-30 19:20:47

标签: javascript reactjs react-router

我是新来的反应者,我想知道如何更改链接/按钮上的单击页面,我已经尝试过以下npm软件包:react-router-dom

问题是,当我单击链接时,URL条目中的路径更改了,但是页面保持不变,这是登录页面代码:

import React, { Component } from "react";
import "jquery/dist/jquery.min.js";
import "bootstrap/dist/js/bootstrap.min.js";
import global from "../resource/global.json";
import { BrowserRouter as Router, Link } from "react-router-dom";

<div className="row" style={{ margin: "auto" }}>
            <div className="row float-left" style={{ margin: "auto" }}>
              <Router>
                <Link
                  to={""}
                  style={{
                    marginRight: "15px",
                    border: "none",
                    color: global.GUI.GRIGIOSCURO,
                    backgroundColor: "transparent",
                    textAlign: "center",
                    textDecoration: "none",
                    display: "inline-block"
                  }}
                >
                  Home
                </Link>
                <Link
                  to={"/terms"}
                  style={{
                    marginRight: "15px",
                    border: "none",
                    color: global.GUI.GRIGIOSCURO,
                    backgroundColor: "transparent",
                    textAlign: "center",
                    textDecoration: "none",
                    display: "inline-block"
                  }}
                >
                  Termini e Condizioni
                </Link>

                <Link
                  to={"/terms"}
                  style={{
                    backgroundColor: "transparent",
                    marginRight: "15px",
                    border: "none",
                    color: global.GUI.GRIGIOSCURO,
                    textAlign: "center",
                    textDecoration: "none",
                    display: "inline-block"
                  }}
                >
                  Privacy
                </Link>
              </Router>
            </div>

这是我的项目目录:

public
|_icon.ico
|_index.html
|_manifest.json
|_src
   |_component 
      |_landing.jsx
      |_login.jsx
      |_terms.jsx

我只想点击链接按钮从登陆到条款,有什么建议吗?难道我做错了什么?谢谢

1 个答案:

答案 0 :(得分:1)

react-router用于根据url更改页面的组件是<Route>。在示例代码中,您没有这些,因此您的页面将永远不会改变。通过路由,您可以指定当url匹配特定模式时,您希望呈现特定组件。

例如,在快速入门部分(found here)中提到了路线渲染

{/* A <Switch> looks through its children <Route>s and
  renders the first one that matches the current URL. */}
<Switch>
  <Route path="/about">
    <About />
  </Route>
  <Route path="/users">
    <Users />
  </Route>
  <Route path="/">
    <Home />
  </Route>
</Switch>

如果url匹配<About/>,则该代码将呈现"/about"组件;如果url匹配<Users/>,则该代码将呈现"/users"组件;否则,将呈现<Home/>组件