javascript - 创建扩展 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 backendImagePath
prop on a DOM element。
第二个问题是另一个警告,即img 元素必须有一个 alt 属性,或者是有意义的文本,或者是用于装饰图像的空字符串。
我的方法是最好的吗?如果是这样,我该如何解决这些警告?
谢谢
解决方案
发生这种情况是因为当您使用扩展运算符 ( {...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} />;
推荐阅读
- c# - 配置中的动态 SQL 连接类
- python-3.x - 无法打破python中的while循环
- java - 从上到下打印整数的 ArrayList 并将每个元素作为字符串返回
- html - 当元素浮动并且是块元素时,剩余边距不起作用
- python - 在 Windows Python 文件中使用 `touch`
- c - 如何从用户那里指定 C 中的 struct 标记?
- c++ - Visual Studio C++中,如何快速找到需要的头文件?
- java - 使用spring-kafka收听kafka主题时出现UnsatisfiedLinkError
- django - Django 渲染
- python - Django 管理自定义