创建扩展img标签的React组件

时间:2018-08-23 13:28:41

标签: javascript reactjs

我正在尝试创建一个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无法识别DOM元素上的backendImagePath道具

第二个问题是另一个警告, img元素必须具有alt道具,该道具必须包含有意义的文本或用于装饰图像的空字符串。

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

谢谢

2 个答案:

答案 0 :(得分:1)

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

相反,您应该通过destructuring props对象来挑选自己的自定义道具,并将其他道具散布到不同的变量中。

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

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

答案 1 :(得分:0)

@Alserda提供的上述解决方案效果很好,但不能抑制开发环境中缺少alt文本的警告。因此,这是最后的代码,在该代码中,我还提取了alt属性并将其显式传递给。

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

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

export default BackendImage;

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