2017-06-19 64 views
1

我有显示在指定的路径图像父组件(注:图像已被保存在我的项目)。该路径可以有其他参数。如果图像不会只显示(但不要否则显示)

例如,图像被显示image)如果HTML路径是:

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文件,因为该组件仍显示当filter在HTML路径(图像刚刚打破,broken)应用,但我提供这只是为了防止我误解了某些东西。

我的组件:

// 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; 

我已经看过并尝试以下一些,但一点运气:

我认为是e是不同的,因为这些主要是与无法显示图像有关的问题。我能够显示图像,但只有当可选的html参数没有设置。

有谁知道为什么图像显示,但只有当没有额外的html参数?

非常感谢。

+0

你是否能够去掉你需要的来源?你可以使用正则表达式来获取图像的URL,而不需要额外的参数。 –

+0

剥去这个源代码可能不是一个合适的解决方案,因为这个图像所在的'img'文件夹中的所有图像都发生了同样的问题,所以这个解决方案意味着剥离整个项目中使用的每个图像将是一个重要的数字) – Rbar

+0

啊好吧,它听起来像你正在使用动态图像路径。那么这些图像已经保存在您的项目中了? –

回答

2

为什么{"img/x.png"}没有访问根目录?如{"/img/x.png"}或将您的env域名设置为全局变量,并在其中添加该域名,否则您正在查看您为img目录命中的每个目录。

+0

美丽!我曾尝试使用'{“./img/x.png”}'(我为React中的'import'语句所做的工作方式),但它并没有解决问题......另一方面,您的解决方案确实如此!逻辑,简单的解决方案。谢谢! – Rbar