[英]Setting dynamic background image in React with create react-app
在下面的 TSX/JSX 中,背景圖片沒有正確加載,因為在編譯過程中 URL 沒有改變,所以它指向了錯誤的位置。
我認為這是一個 webpack 配置問題。 過去,我手動設置了 React 應用程序,但我對創建 react-app 還很陌生。 我需要彈出並進行一些手動配置,還是有更好的方法來動態加載我丟失的背景圖像?
{section.stops.map(s => (
<div
className="tour-stop"
style={{
backgroundImage: `url(./img/${s.imagePath})`
}}
>
blah blah blah
</div>
))}
要為組件渲染的stops
動態設置背景圖像,請考慮使用<div>
或<React.Fragment>
等元素包裝從render()
返回的項目列表,而不是{ .. }
括號作為如下圖:
.tour-stop { padding:5rem; text-align:center; }
<div id="module"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.7.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.7.0/umd/react-dom.production.min.js"></script> <script type="text/babel"> class DemoComponent extends React.Component { constructor(props) { super(props); /* Prepopulate the state of the component with image data for subsequnet the render */ this.state = { section : { stops : [ { imagePath : 'https://wallpaperbrowse.com/media/images/background-wallpapers-26.jpg' }, { imagePath : 'https://wallpaperbrowse.com/media/images/704532.jpg' }, { imagePath : 'https://wallpaperbrowse.com/media/images/abstract-background-design_1297-88.jpg' } ] } } } render() { /* Access the section object from state, by which the stops will be rendered */ const { section } = this.state; /* Ensure that the list result returned is wrapped with an element. Usually <div> is used to wrap results however <React.Fragment> can also be useful */ return <div>{ section.stops.map(s => (<div className="tour-stop" style={{ backgroundImage: `url(${s.imagePath})` }}> blah blah blah </div>)) }</div> } } ReactDOM.render( <div> <DemoComponent /> </div>, document.getElementById("module")); </script>
希望這可以幫助!
不幸的是,您必須對目錄中的任何 URL 進行硬編碼。 您必須編寫一個選擇精確圖像的條件。 如果它的 URL 來自數據庫/其他任何地方,則情況並非如此。
您的代碼中的一個示例是(沒有任何編碼)是,
如果s.imagePath
是'val1'
,請使用此圖像: './img/1.jpeg'
如果不是,請使用任何內容。
只有當您在自己的目錄中獲取資產時才會發生這種情況。
這是我的解決方案:
<div className="drag-dashboard" style={{ backgroundImage: `url(${config.DESTINATION_MEDIA_CDN+ "assets/icons_skining/upload_placeholder_skining.png"})`}}> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.