首页 > 解决方案 > 创建扩展 img 标签的 React 组件

问题描述

我正在尝试创建一个从远程位置呈现图像的 React 组件。我希望它继承传递的任何道具,例如 alt、style、className 等。我不知道这些道具是什么提前。

我设法这样写,但我有以下描述的问题:

import React, { Component } from "react";
import PropTypes from "prop-types";

class BackendImage extends Component {
  render() {
    const remoteImageURL = process.env.REACT_APP_BACKEND_URL + this.props.backendImagePath;
    return <img {...this.props} src={remoteImageURL} />;
  }
}

export default BackendImage;

BackendImage.propTypes = {
  backendImagePath: PropTypes.string,
};

第一个问题是我将 prop backendImagePath 传递给无法识别它的 img,因此抛出警告React does not identify the backendImagePathprop on a DOM element

第二个问题是另一个警告,即img 元素必须有一个 alt 属性,或者是有意义的文本,或者是用于装饰图像的空字符串。

我的方法是最好的吗?如果是这样,我该如何解决这些警告?

谢谢

标签: javascriptreactjs

解决方案


发生这种情况是因为当您使用扩展运算符 ( {...this.props}) 时,您也在扩展 的backendImagePath内部img,这是不允许的。

相反,您应该通过解构props 对象并将其他 props 分布在不同的变量中来挑选自己的自定义 props 。

const { backendImagePath, ...rest } = this.props;

const remoteImageURL = process.env.REACT_APP_BACKEND_URL + backendImagePath;
return <img {...rest} src={remoteImageURL} />;

推荐阅读