繁体   English   中英

为什么 document.getElementById() 在 React 中返回 null 尽管 React 中有元素?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM