【问题标题】:How to import images dynamically to set as the url path for background image property in react如何动态导入图像以设置为反应中背景图像属性的url路径
【发布时间】:2020-10-07 19:11:01
【问题描述】:

我有一个资产文件夹来存储我的所有图像。
在资产文件夹中,我还有一个 json 文件,其中包含对象,每个对象都有一个保存图像相对路径的键。

[
  {"url":"../assets/image1"},
  {"url":"../assets/image1"}
]

我希望能够通过 json 文件中的这些对象进行映射,并动态创建一个组件,该组件将具有一个 div,其中它的 background-image 属性将是一个 url(),并且路径的参数将通过每个提供json 对象。
像这样:

function Box(props) {
  const style = {
    backgroundImage: `url(${props.imageURL})`
  }
  return(<div style={style}></div>)
}

如果我在顶部专门导入这样的图像路径,它会起作用

import imageURL from '../assets/image1';
...
    backgroundImage: `url(${imageURL})`
...

但是那样它就不会是动态的。

如何动态导入导入图片以设置为 background-image 属性的 url 路径?

【问题讨论】:

    标签: reactjs url webpack import background-image


    【解决方案1】:

    受@chonnychu 启发的答案
    我最终制作了一个处理所有导入的组件,并在最后导出所有导入的东西。
    虽然这不是最佳解决方案,但它的手动工作量是可以接受的。

    import box1image from "../assets/TimeSeriesAnalysis.png";
    
    const boxInfo = [
      {
        id: 1,
        image: box1image,
        title: "Box 1",
        description:
          "Box 1 is the first box",
      },
    ];
    
    export default boxInfo;
    

    【讨论】:

      【解决方案2】:

      如果您有一个用于映射所有图像 url 的对象,也许您可​​以这样做吗?

      你的地图文件

      import bg from './bg.jpg';
      import bg1 from './bg1.jpg';
      
      export default {
        bg,
        bg1,
        ...
      }
      

      你的组件

      import imageMap from '../assets/imageMap';
      
      function Box() {
        const [imageUrl, setImageUrl] = React.useState(imageMap.bg);
      
        React.useEffect(() => {
          /* you can change image url by effects dynamically */
        }, [])
      
        /* you can change image url by events dynamically too */
        const handleClick = () => {
          setImageUrl(imageMap.bg1);
        }
      
        return (
          <div
            style={{
              backgroundImage: `url(${imageUrl})`
            }}
            onClick={handleClick}
          />
        )
      }
      

      【讨论】:

        猜你喜欢
        • 2019-07-12
        • 1970-01-01
        • 2023-03-28
        • 1970-01-01
        • 2019-03-24
        • 1970-01-01
        • 1970-01-01
        • 2020-01-01
        • 1970-01-01
        相关资源
        最近更新 更多