2017-06-19 54 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