我正在尝试创建一个从远程位置渲染图像的 React 组件。我希望它继承传递的任何 Prop ,例如 alt、style、className 等。我提前不知道这些 Prop 是什么。
我设法这样写,但我遇到了以下问题:
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,
};
第一个问题是我将 backendImagePath 属性传递给无法识别它的 img,因此抛出警告 React 无法识别 DOM 元素上的 backendImagePath
属性.
第二个问题是另一个警告:img 元素必须有 alt 属性,要么是有意义的文本,要么是用于装饰图像的空字符串。
我的方法是最好的吗?如果是这样,我该如何解决这些警告?
谢谢
最佳答案
发生这种情况是因为当您使用展开运算符 ({...this.props}
) 时,您也在 内部展开
,这是不允许的。backendImagePath
img
相反,您应该通过 destructuring 选择您自己的自定义 Prop props 对象,并将其他 props 分布在不同的变量中。
const { backendImagePath, ...rest } = this.props;
const remoteImageURL = process.env.REACT_APP_BACKEND_URL + backendImagePath;
return <img {...rest} src={remoteImageURL} />;
关于javascript - 创建扩展 img 标签的 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51986937/