[英]Import images in react in a loop
我要完成的工作是從正確的目錄導入每個文件。 我的后端代碼將文件保存到images目錄,而我的前端目錄是我存放React.js代碼的位置。
我的目錄結構可以在下面看到。
-- Backend
-- backend code
-- Frontend
-- frontend code
-- images
-- user_1
-- People.jpg
-- user_2
...
如您所見,我正在從后端獲取路徑。 imagePath將類似於以下“ ../images/user_1/People.jpg”。 我看到另一個stackoverflow post使用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>
);
}
}
回答
而不是在目錄中提供image標簽的路徑。 我將backen配置為通過url檢索照片。
capsule.imagePath => http:// localhost:8000 / snapcapsule / images / user_1 / People.jpeg
我建議避免動態條件的動態需求。 捆綁時,它可能不會包括您的所有圖像,並且可能會引起問題。
在您的情況下,您正在從服務器中獲取信息,並嘗試直接從文件夾中導入文件,這是不正確的方式。 作為Web應用程序,您應該使用Web URL顯示圖像。
響應capsuleList,您具有圖像路徑。 使用該路徑,您的后端應處理請求並返回圖像。 這是后端責任。 當React在瀏覽器上運行時,React沒有訪問文件夾的權限,但是您的后端可以訪問文件夾。
在您的后端中,讀取圖像並進行服務器處理。
您應該實際上可以直接在縮略圖組件中引用這些圖像,而無需將其導入為模塊或類似的內容。
const path = "./../../images/user_1/People.jpg";
<Thumbnail src={path} ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.