简体   繁体   English

REACT:当子组件有错误时隐藏父组件

[英]REACT : hide parent component when child component has an error

I have components like this我有这样的组件

  • < Parent container> <父容器>
    • < image description> <图片说明>
    • < image container> <图像容器>
      • < image tag> <图片标签>
      • < image caption text> <图片说明文字>

how this works is parent container has a name of a city which it passes down to image container这是如何工作的,父容器有一个城市的名字,它传递给图像容器

which makes a search query with that city to make some image URL使用该城市进行搜索查询以生成一些图像 URL

now that image url is passed to image tag现在图像 url 被传递给图像标签

now when that image url is failing to fetch source, image is coming as blank, but other things like image description which are higher up in heirarchy are still showing up..现在,当该图像 url 无法获取源时,图像变为空白,但其他诸如在层次结构中较高的图像描述之类的内容仍在显示..

I can handle image load failure at image container level maybe, but how to percolate this to parent container so that parent container itself hides when image load fails我可以在图像容器级别处理图像加载失败,但是如何将其渗透到父容器,以便在图像加载失败时父容器本身隐藏

I'd recommend giving this a read around Lifting state我建议阅读有关提升状态的内容

It sounds to me like you're making an API call to get an image, which may not always exist, and then to render other components based on this.在我看来,您正在调用 API 来获取可能并不总是存在的图像,然后基于此渲染其他组件。 The API call could be lifted to the top parent container, and render the child components based on the result of this call. API 调用可以提升到顶部父容器,并根据此调用的结果呈现子组件。

The parent makes the call to get the image, and then there you can decide what you want to render based on success or failure. parent调用获取图像,然后您可以根据成功或失败决定要渲染的内容。

You can simply pass in a callback prop for this type of event:你可以简单地为这种类型的事件传入一个回调道具:

function ImageComponent({ imageSrc, onImageLoadError }) {
  return (
    <img onError={onImageLoadError} src={imageSrc} />
  );
}

and then in you ParentComponent:然后在你的 ParentComponent 中:

function ParentComponent() {
  const [imgSrc, setImgSrc] = React.useState("some_image_url");
  const handleImageLoadError = () => {
    // do something in case of error (show a default image etc)
    setImgSrc('default_image_which_loads');
  };

  return (
    <ImageComponent imageSrc={imgSrc} onImageLoadError={handleImageLoadError} />
  )
}

or if you want to hide the image component you can do that as well:或者如果你想隐藏图像组件,你也可以这样做:

function ParentComponent() {
  const [imgHasError, setImgHasError] = React.useState(false);
  const handleImageLoadError = () => {
    // hide image in case of error
    setImgHasError(true);
  };

  return (
    {imgHasError ? null : (<ImageComponent imageSrc={imgSrc} onImageLoadError={handleImageLoadError} />)}
  )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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