[英]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.