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

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

我可以通过导入图像并使用 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

但是当我尝试这样的动态方法时:

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'
  }
}))

没有图像显示,我得到这个值:

 backgroundImage: url([object object])

感谢任何帮助。

根据 docs:

useStyles. It accepts one argument: the properties that will be used for "interpolation" in the style sheet.

基本上,makeStyles 回调中的参数表示您的 theme,它是一个对象。为了在 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)
...