[英]Why is document.getElementById() returning null in React although element is there in React?
I have this code inside a React class component and when I try calling document.getElementById(photo._id)
it keeps returning null although when I tried console.log(photo._id)
in both lines, the line in the render is printed first in the console so the id is supposed to be there?我在 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} />;
})}
)
}
You are not returning the image element in map function. Hence, it's not mounted in the dom tree and you can't access it using document.getElementById()您没有返回 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} />;
})}
)
}
Replace your render function body with the code below.用下面的代码替换你的渲染 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.