首页 > 解决方案 > 如何将道具动态发送到材质 UI 中的样式挂钩?

问题描述

我正在尝试向 div 添加动态背景图像。我正在映射一组对象以返回 div。如何根据对象中的图像 URL 向 div 添加背景图像?

这是代码。

const useStyles = makeStyles({
div: (props) => ({
width: "100px",
height: 0,
paddingBottom: "100px",
backgroundImage: "how do i know which image to pull",
 }),
});

let arr = [
       { photo_url: "some url" },
       { photo_url: "some url" },
       { photo_url: "some url" },
       ];

function Test() {
   const classes = useStyles("how do i send image of that specific object");
   return arr.map((obj) => <div className={classes.div}></div>);
   }

编辑:为了简单起见,我选择使用 style 属性添加动态样式,使用 className 属性添加所有 div 通用的通用样式。

标签: javascriptcssreactjsmaterial-uifrontend

解决方案


将数组发送到 useStyles:

   const classes = useStyles(array);

现在在 makeStyles 中接收数组:

  const useStyles = makeStyles(array=>{
    let divStyles={} 

// create dynamic styles based on the index of the .div class:

  array.forEach((bgUrl,index)=>{
      divStyles[`&:nth-child(${index+1})`]={ // because the index starts at zero
        width: "100px",
        height: 0,
        paddingBottom: "100px",
        backgroundImage: bgUrl,
         }
  })
  return {div:divStyles}
});

推荐阅读