简体   繁体   English

在 jss 中为 backgroundImage 动态插入 url 时,我没有得到任何图像。 反应, material-ui

[英]I get no image when dynamically inserting a url in jss for backgroundImage. React, material-ui

I can get the image statically displayed by importing it and using the variable in useStyles as in the following chunk:我可以通过导入图像并使用 useStyles 中的变量来静态显示图像,如下面的块所示:

import React from 'react'
import { makeStyles } from '@material-ui/core/styles'
import { Box } from '@material-ui/core'
import Image from '../../Images/Shanghai.png'

const useStyles = makeStyles(img => ({
  image: {
    backgroundImage: 'url('+ image +')',
    backgroundPosition: 'center',
    width: '100%',
    height: '10rem',
    backgroundSize: 'cover'
  }
}))

const ImageHeader = props => {
const img = props.img
const classes = useStyles(img)

return <Box sm={12} className={classes.image} />
    }

export default ImageHeader

but when I try a dynamic approach like so:但是当我尝试这样的动态方法时:

import React from 'react'
import { makeStyles } from '@material-ui/core/styles'
import { Box } from '@material-ui/core'

const useStyles = makeStyles(img => ({
  image: {
    backgroundImage: 'url(' + img + ')',
    backgroundPosition: 'center',
    width: '100%',
    height: '10rem',
    backgroundSize: 'cover'
  }
}))

No image is displayed and I get this value:没有图像显示,我得到这个值:

 backgroundImage: url([object object])

Any help appreciated.任何帮助表示赞赏。

As per the docs :根据文档

useStyles.使用样式。 It accepts one argument: the properties that will be used for "interpolation" in the style sheet.它接受一个参数:将用于样式表中“插值”的属性。

Basically, the argument in makeStyles callback represents your theme which is an object. In order to use the argument passed to useStyles in makeStyles 's callback, you have to use the callback approach for the backgroundImage property.基本上, makeStyles回调中的参数代表您的theme ,即 object。为了在makeStyles的回调中使用传递给useStyles的参数,您必须对backgroundImage属性使用回调方法。

...
const useStyles = makeStyles(theme => ({ // <---------- theme is an object
  image: {
    backgroundImage: (image) => 'url('+ image +')', // <---------- like this
    backgroundPosition: 'center',
    width: '100%',
    height: '10rem',
    backgroundSize: 'cover'
  }
}))

const ImageHeader = props => {
const img = props.img
const classes = useStyles(img)
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM