gh-pages上的React app:无法链接到本地 文件

问题描述 投票:1回答:1

如果我创建一个react应用程序,并且在这个应用程序中有一个本地html文件的链接,一旦这个应用程序在gh-pages上发布,由于某些原因所述链接不会导致任何地方,它只是将用户重定向到同一页面上在点击链接之前进入。

例如:

如果我用CRA创建一个简单的应用程序,如下所示:

App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        I'm the homepage
        <a id='testlink' href='html2.html'> Go to the second page </a>
      </div>
    );
  }
}

export default App;

在公共文件夹中,我创建了一个新的html文件“html2.html”,简单地说

I am the second app !

就是这样,一个简单的应用程序应该在点击链接时从index.html跳转到html2.html。那么这个应用程序在使用npm start进行测试时工作正常,如果通过npm run build提供的静态html文件启动它可以正常工作,但是当部署在gh-pages上时,该链接不会导致任何地方。

Here is the app described above deployed on ghpages

解决这个问题的一个方法是在gh-pages上单独上传所有应用程序,或者使用react路由器,但我想知道我是否只是遗漏了一些东西。谢谢你的帮助。

html reactjs href github-pages
1个回答
1
投票

React项目中,您应该使用react-router来处理routes并更改页面。

简单的例子:

import React from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

const BasicExample = () => (
  <Router>
    <div>
      <ul>
        <li>
          <Link to="/">Home</Link>
        </li>
        <li>
          <Link to="/about">About</Link>
        </li>
        <li>
          <Link to="/topics">Topics</Link>
        </li>
      </ul>

      <hr />

      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
      <Route path="/topics" component={Topics} />
    </div>
  </Router>
);

const Home = () => (
  <div>
    <h2>Home</h2>
  </div>
);

const About = () => (
  <div>
    <h2>About</h2>
  </div>
);

const Topics = ({ match }) => (
  <div>
    <h2>Topics</h2>
    <ul>
      <li>
        <Link to={`${match.url}/rendering`}>Rendering with React</Link>
      </li>
      <li>
        <Link to={`${match.url}/components`}>Components</Link>
      </li>
      <li>
        <Link to={`${match.url}/props-v-state`}>Props v. State</Link>
      </li>
    </ul>

    <Route path={`${match.url}/:topicId`} component={Topic} />
    <Route
      exact
      path={match.url}
      render={() => <h3>Please select a topic.</h3>}
    />
  </div>
);

const Topic = ({ match }) => (
  <div>
    <h3>{match.params.topicId}</h3>
  </div>
);

export default BasicExample;
© www.soinside.com 2019 - 2024. All rights reserved.