javascript - 如何将道具动态发送到材质 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 通用的通用样式。
解决方案
将数组发送到 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}
});
推荐阅读
- rest - 不存在的对象的 GraphQL 查询结果
- go - go protobuf:找不到包“。” 在 github.com/gogo/protobuf/proto 和 m.TimeStamp.MarshalToSizedBuffer 中未定义
- sql - 我真的不明白出了什么问题
- c# - c#中的秒表(统一)
- vim - 获取“按 ENTER 或键入命令继续”,有关如何解决的任何提示?
- c++ - 为什么未删除的文件指向无效的 NTFS MFT 记录?
- r - 从1到N生成序列的速度
- c++ - config_stream.is_open() c++ 总是返回 false
- python - 在 Raspberrypi (Systemd) 中重新启动时使用 scapy 嗅探
- java - 可以暂停/恢复并执行用户的可运行操作的通用线程