gpt4 book ai didi

javascript - react 图像未在多站点页面上加载

转载 作者:行者123 更新时间:2023-11-28 00:23:03 27 4
gpt4 key购买 nike

我正在用 React 开发一个多页面网站。问题是,当我从一页转到另一页时,我丢失了图像。它们在根页面 "/" 上工作正常,但是当我转到另一个页面 ( company1 ) 时, Logo 丢失了。

在浏览器控制台中,当我导航到 company1 时,我收到错误:company1.jpg:1 GET http://localhost:8080/company/images/company1.jpg 404(未找到)

我看不出这里出了什么问题 - 我直接在 Navbar.js 组件中导入图像。

我的文件结构


└public
│ + index.html
|
└src
| └───components
| │ + Navbar.js
| | + Footer.js
| |
| └───img
| │ └───companies
| | | + company1.jpg
| | | + company2.jpg
| | + logo.png
| │
| └───pages
| | + Home.js
| | + Company1.js
| | + Company2.js
| |
| └───routes
| │ + AppRouter.js
| │
| + app.js
|
+ webpack.config.js

routes/AppRouter.js

import React from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import Footer from "../components/Footer";
import Home from "../pages/Home";
import Company1 from "../pages/Company1";
import Company2 from "../pages/Company2";

const AppRouter = () => (
<BrowserRouter>
<div>
<Switch>
<Route path="/" component={Home} exact={true} />
<Route path="/company/company1" component={Company1} />
<Route path="/company/company2" component={Company2} />
</Switch>
<Footer />
</div>
</BrowserRouter>
);

export default AppRouter;

/pages/Home.js

import React from "react";
import Navbar from "../components/Navbar";
export default class Home extends React.Component {
render() {
return (
<div>
<Navbar company="GROUP PAGE" />
</div>
);
}
}

/pages/Company1.js

import React from "react";
import Navbar from "../components/Navbar";
const Company1 = () => (
<div>
<Navbar company="Company1" />
</div>
);

export default Company1 ;

/components/Navbar.js

import React from "react";
import { Link } from "react-router-dom";
import logo from "../img/logo.png";

const Navbar = props => (
<nav>
<Link className="navbar-brand to="/">
<img src={logo} width="120" height="50" alt="group" />
<span>{props.company}</span>
</Link>
</nav>
);

export default Navbar;

webpack.config.js

const path = require("path");
module.exports = {
entry: "./src/app.js",
output: {
path: path.join(__dirname, "public"),
filename: "bundle.js"
},
module: {
rules: [
{
loader: "babel-loader",
test: /\.js$/,
exclude: /node_modules/
},
{
test: /\.s?css$/,
use: ["style-loader", "css-loader", "sass-loader"]
},
{
test: /\.(png|jp(e*)g|svg)$/,
use: [
{
loader: "url-loader",
options: {
limit: 8000, // Convert images < 8kb to base64 strings
name: "images/[hash]-[name].[ext]"
}
}
]
}
]
},
devtool: "cheap-module-eval-source-map",
devServer: {
contentBase: path.join(__dirname, "public"),
historyApiFallback: true
}
};

最佳答案

如果图像在 src/assets 文件夹中,您可以使用 require。

const img = require('../../img.png');

您也可以内联执行此操作

<img src={require('../../img.png')} />

关于javascript - react 图像未在多站点页面上加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54786241/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com