[英]Why is document.getElementById() returning null when there is an element with that Id?
[英]Why is document.getElementById() returning null in React although element is there in React?
我在 React class 組件中有這段代碼,當我嘗試調用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} />;
})}
)
}
您沒有返回 map function 中的圖像元素。因此,它沒有安裝在 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} />;
})}
)
}
用下面的代碼替換你的渲染 function 主體。
return this.props?.location?.state?.product?.photos?.map((photo) =>
<img key={photo._id} id={photo._id} src={...} />;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.