我正在使用 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/