我在 React 類組件中有這段代碼,當我嘗試呼叫document.getElementById(photo._id)它時,它一直回傳 null,盡管當我console.log(photo._id)在這兩行中都嘗試時,渲染中的行首先在控制臺中列印,所以 id 應該在那里?
componentDidMount() {
this.props.location.state.product.photos.map((photo) => {
return axios
.get(`${SERVER_HOST}/products/photo/${photo.filename}`)
.then((res) => {
if (res.data) {
if (res.data.errorMessage) {
console.log(res.data.errorMessage);
} else {
console.log(photo._id);
console.log(document.getElementById(photo._id));
}
} else {
console.log("Record not found");
}
});
});
}
render() {
return (
{this.props.location.state.product.photos.map((photo) => {
{ console.log(photo._id); }
<img key={photo._id} id={photo._id} />;
})}
)
}
這是控制臺的圖片
uj5u.com熱心網友回復:
您沒有在 map 函式中回傳影像元素。因此,它沒有安裝在 dom 樹中,您無法使用 document.getElementById() 訪問它
render() {
return (
{this.props.location.state.product.photos.map((photo) => {
{ console.log(photo._id); }
{/** return keyword is missing here **/}
return <img key={photo._id} id={photo._id} />;
})}
)
}
uj5u.com熱心網友回復:
用下面的代碼替換你的渲染函式體。
return this.props?.location?.state?.product?.photos?.map((photo) =>
<img key={photo._id} id={photo._id} src={...} />;
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/433092.html
標籤:javascript 反应 dom
