我有一个在指定路径显示图像的父组件(注意:图像已经保存在我的元素中)。此路径可以选择具有其他参数。如果
例如,如果 html 路径为:
,则显示图像 ( image ) www.mysite.com/myPath
组件显示但图像损坏 ( broken image ) 如果 html 路径是:
www.mysite.com/myPath/someFilterForThisPage
路由器
// Libraries
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import { browserHistory } from 'react-router';
// Components
import Home from './containers/Home';
import NotFound from './components/NotFound';
import MyComponent from './components/MyComponent';
// Redux
import { Provider } from 'react-redux';
import {createStore} from 'redux';
import allReducers from './reducers';
const store = createStore(
allReducers,
window.devToolsExtension && window.devToolsExtension()
);
// Routes
const routes = (
<Router history={browserHistory}>
<div>
<Provider store={store}>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/myPath/:filter?" component={MyComponent} />
<Route component={NotFound} />
</Switch>
</Provider>
</div>
</Router>
);
export default routes;
我不认为问题出在我的 router.js 文件上,因为当在 html 路径中应用 filter
时组件仍然显示(图像刚刚损坏,),但我提供它以防万一我误解了什么。
我的组件:
// React
import React from 'react';
class MyComponent extends React.Component {
constructor(props) {
super(props);
}
render() {
<div>
<img src={"img/x.png"} id="someId" alt=""/> // ISSUE
// ...
// some divs that show/don't based on the filter of the html path
// ...
</div>
}
}
export default MyComponent;
我查看并尝试了以下一些方法,但运气不佳:
我认为这些是不同的,因为这些主要是与根本无法显示图像有关的问题。我能够显示图像,但前提是未设置可选的 html 参数。
有谁知道为什么显示图像,但前提是没有额外的 html 参数?
非常感谢。
最佳答案
{"img/x.png"}
没有访问 root 的原因是什么?例如 {"/img/x.png"}
或将您的 env 域设置为全局变量并将其添加到其中,否则您将在每个目录中查找 img 目录。
关于javascript - 图像仅在提供可选的 html 参数时不显示(否则显示),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44639139/