如何在Material UI中向样式钩子动态传递props设置div背景图
解决方案
方案1:style+className分离实现(符合你要求的简化方案)
你可以把所有div通用的固定样式放到makeStyles的公共类里,仅把动态的背景图通过style属性单独设置,实现逻辑最简洁:
// 只写通用公共样式,不需要接收props const useStyles = makeStyles({ commonDiv: { width: "100px", height: 0, paddingBottom: "100px", // 其他通用样式都可以加在这里 }, }); const arr = [ { photo_url: "some url1" }, { photo_url: "some url2" }, { photo_url: "some url3" }, ]; function Test() { const classes = useStyles(); return arr.map((obj, index) => ( <div key={index} // 记得加key属性避免React警告 className={classes.commonDiv} style={{ backgroundImage: `url(${obj.photo_url})` }} ></div> )); }
方案2:纯makeStyles传参实现(无内联样式版)
如果你不想使用内联style,可以把单个div抽为独立小组件,在组件内调用useStyles时传入当前图片url即可:
const useStyles = makeStyles({ div: (props) => ({ width: "100px", height: 0, paddingBottom: "100px", backgroundImage: `url(${props.imgUrl})`, }), }); const arr = [ { photo_url: "some url1" }, { photo_url: "some url2" }, { photo_url: "some url3" }, ]; // 抽离单个图片div组件 function ImgDiv({imgUrl}) { const classes = useStyles({imgUrl}); return <div className={classes.div}></div> } function Test() { return arr.map((obj, index) => <ImgDiv key={index} imgUrl={obj.photo_url} />); }
内容的提问来源于stack exchange,提问作者Hyphen Frox
相关产品推荐
相关产品推荐

