【发布时间】:2018-12-05 20:13:17
【问题描述】:
我想要完成的是从正确的目录导入每个文件。我的后端代码将文件保存到 images 目录,而我的前端目录是我保存 React.js 代码的地方。
我的目录结构如下所示。
-- Backend
-- backend code
-- Frontend
-- frontend code
-- images
-- user_1
-- People.jpg
-- user_2
...
如您所见,我正在从后端获取路径。 imagePath 看起来像这样“../images/user_1/People.jpg”。我看到另一个 stackoverflow 帖子使用 require 关键字将图像存储在 const 变量中,但我使用该方法收到错误。
@observer
export default class SnapCapsule extends React.Component {
componentDidMount() {
axios.get(`${this.props.domain}/snapcapsule`)
.then(res => {
res.data.map((capsule) => {
var domainSize = this.props.domain.length+13;
var imagePath = "../" + capsule["image"].substring(domainSize);
var dateToPost = capsule["dateToPost"].substring(0, 10);
var username = capsule["username"];
console.log(capsule["caption"], imagePath, dateToPost, username);
this.props.store.addCapsule(
capsule["caption"],
imagePath,
dateToPost,
username
)
})
});
}
componentWillUnmount() {
this.props.store.clear();
}
render() {
const { capsules } = this.props.store;
const capsuleList = capsules.map((capsule, i) => (
<Col key={i} xs={6} md={4}>
<Thumbnail src={capsule.imagePath} alt="242x200">
<h3> {capsule.title} </h3>
<p> @{capsule.username} </p>
</Thumbnail>
</Col>
));
return (
<Grid>
<Row>
{ capsuleList }
</Row>
</Grid>
);
}
return (
<Grid>
<Row>
{ capsuleList }
</Row>
</Grid>
);
}
}
回答
而不是提供目录中图像标签的路径。我将后台配置为通过 url 检索照片。
capsule.imagePath => http://localhost:8000/snapcapsule/images/user_1/People.jpeg
【问题讨论】:
标签: javascript html reactjs webpack