node.js - 如何在reactjs中显示svg图像

标签 node.js reactjs svg axios react-bootstrap

我正在使用 Nodejs 和 Reactjs 开发一个 Web 应用程序,目前我正在从 mongo 数据库中检索数据并使用 React 显示它。

这是一些代码:

import React, {Component} from 'react';
import axios from '../../node_modules/axios';
import {Col,Card} from 'react-bootstrap';

import {BrowserRouter as Router,Link, useRouteMatch} from 'react-router-dom';

const Brand = props => (
<Col lg="4" className="d-inline-block">
  <Link to="/admin/Marques/MarqueDetails/1">
  <Card className="marque-card" style={{ width: '100%' }}>
      <p>{props.brand.name}</p>
      <Card.Img className="marque-card" variant="top" src={`../../public/` + 
       props.brand.imgUrl} />
  </Card>
  </Link>
</Col>
)

class cardBrand extends Component {

constructor(props) {
    super(props);

    this.state = {brands: []};
  }
  componentDidMount() {
    axios.get('http://localhost:5000/brand/')
      .then(response => {
        this.setState({ brands: response.data })
      })
      .catch((error) => {
        console.log(error);
      })
  }
  brandList() {
    return this.state.brands.map(currentBrand => {
      return <Brand brand={currentBrand} key={currentBrand._id}/>;
    })
  }
render() {
    return(
      <Col lg="12">
       { this.brandList() }
       </Col>
    )
  }
}
export default cardBrand;

如您所见,我的 public 文件夹中有 img/brand 文件夹,并且 props.brand.imgUrl 包含路径和图像名称,但不幸的是它在浏览器上不起作用,这是一个图像:

P.S:我已经尝试过 react-svg 但什么也没发生,也许是因为我不知道如何使用它。 预先感谢您。

最佳答案

从屏幕截图来看,您的 svg 路径似乎是 img/brand/svg-name.svg。要显示图像,请不要在源中包含 public 。例如,要在 public/img/brand 中显示图像,您可以使用

// without specifying public directory
<img alt="test" src={'/img/brand/svg-name.svg'}/>

将您的卡 src 更改为

<Card.Img className="marque-card" variant="top" src={`/${props.brand.imgUrl}`} />

关于node.js - 如何在reactjs中显示svg图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60285172/

相关文章:

javascript - Discord.js:如何获取对带有特定表情符号的消息使用react的所有用户,然后将用户列表设置为变量?

php - 使用回调在 Node js 中全局访问变量

reactjs - 来自 create-react-app 的 Jest 未在 Windows 上运行

node.js - 具有自定义属性的文件对象

css - 如何将自定义 SVG 文件与 material-ui 图标组件一起使用?

editor - 有什么好的小型或基础SVG编辑器?

javascript - 尝试连续使用 async.forEach 但失败 - Node.js

javascript - 向函数组件添加状态和生命周期方法

javascript - 将 HTML 附加到 d3 中的现有工具提示

mysql - Sequelize ORM 连接干净退出