React Router,保护静态图片

时间:2019-04-15 11:49:56

标签: javascript reactjs react-router

我已经使用react创建了一个网站。网页的图片可使用url访问,例如- http://localhost:3000/1.jpg

我想保护而不是在公用文件夹中显示该图像, 我尝试了下面的代码,如果我在url中提供图像名称点扩展名,则无法使用,如果公用文件夹中不存在该名称图像,则可以使用

import React, { Component } from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import App from "../App";
import PageNotFound from "../components/PageNotFound/PageNotFound";

class Router extends Component {
  render() {
    return (
      <BrowserRouter>
        <Switch>
          <Route exact path="/" component={App} />
          <Route path="*" component={PageNotFound} />
        </Switch>
      </BrowserRouter>
    );
  }
}

export default Router;

1 个答案:

答案 0 :(得分:0)

建议将图像放在文件夹public/images中(通常按照惯例) 然后做这样的事情

import React, { Component } from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import App from "../App";
import PageNotFound from "../components/PageNotFound/PageNotFound";

class Router extends Component {
  render() {
    return (
      <BrowserRouter>
        <Switch>
          <Route exact path="/" component={App} />
          <Route path="*" component={PageNotFound} />
          <Route path="/images/public/*" component={PageNotFound} />
        </Switch>
      </BrowserRouter>
    );
  }
}

export default Router;