首页 > 解决方案 > Reactjs img 标签没有在 src: 中呈现字符串?

问题描述

我正在尝试在 reactjs 中渲染图像。我正在处理一个 URL 并将其存储在一个全局 var URL 中。我想在 img 标签 src 中使用填充的 URL:

我尝试过以下操作,但没有奏效

<img
        src={url}

        style={{
          marginTop: '1px',
          marginLeft: '1px',
          marginBottom: '1px',
        }}
        height="500"
        alt=""
      />

我的元素检查显示以下内容:

<img src height="500" alt="" style="margin-top: 1px; margin-left: 1px; margin-bottom: 1px;">
var url = '';
export default function ImageGallery() {

  const classes = useStyles()
  getList()
  return (
    <div>
    <Paper className={classes.root}>
      <img
        src={{url}}

        style={{
          marginTop: '1px',
          marginLeft: '1px',
          marginBottom: '1px',
        }}
        height="500"
        alt=""
      />
            <Link to={'/imageGalleryGrid'} style={{ textDecoration: 'none' }}>
              <Button variant="contained" className={classes.button}  style={{
                                                                               marginTop: '1px',
                                                                               marginLeft: '550px',
                                                                               marginBottom: '70px',
                                                                             }}>
                Checkout Gallery
              </Button>
            </Link>
      </Paper>



    </div>
  )
}

图像未显示:我在控制台中看到 URL 正在打印。另外,我可以转到 URL 并查看图像。

标签: javascriptreactjs

解决方案


它应该是

<img
  src={url}
  // ...
/>;

whereurl必须是一个字符串

如果添加另一对花括号,它将变成一个对象。

双花括号语法仅在您想内联定义对象时使用,例如当您定义内联样式时style={{color: 'red'}}

如果你想硬编码 url 来测试它,你可以这样做:

<img
  src="https://feelingfoodish.com/wp-content/uploads/2012/08/New-York-Style-pizza.jpg"
  // ...
/>;

推荐阅读