javascript - 如何使用 img.src 构造渲染函数
问题描述
我的render()
函数中有以下代码,并且每当发生状态更改时,我都会尝试动态更改图像的高度和宽度:
render() {
const imageURL = photos[this.state.currentImage].url;
const base_image = new Image();
base_image.src = imageURL;
var wrh = base_image.width / base_image.height;
var newWidth = 600;
var newHeight = newWidth / wrh;
return (
<img height={newHeight} width={newWidth}>
)
}
我知道我必须添加一个base_image.onload
函数来确保何时base_image.src
设置图像开始加载,但代码跳转到return()
并呈现错误height
和width
值的图像,因为图像没有完成加载并且我没有获取正确的值。base_image
如何构建我的代码,以便在完成加载之前不会渲染图像?
解决方案
您可以使用 astate variable
来存储图像的比率。在该render
方法中,您可以使用条件渲染来防止显示图像,直到计算出比率
const width = 600;
class YourComponent {
constructor(props) {
super(props);
this.state = {
ratio: undefined,
currentImage: 0
};
this.image = new Image();
}
componentDidMount() {
this.img.onload = () => {
this.setState({
ratio: this.img.naturalWidth / this.img.naturalHeight
});
};
this.img.src = photos[this.state.currentImage].url;
}
componentDidUpdate(prevProps, prevState) {
if (this.state.currentImage !== prevState.currentImage) {
this.img.src = photos[this.state.currentImage].url;
}
}
render() {
const {ratio} = this.state;
return ratio && <img width={width} height={width/ratio}>;
}
}
推荐阅读
- arrays - 从文本文件 C 中获取 2d char 数组维度和内容
- json - Ktor 动态文件路径
- cupy - Cupy 错误:模块 'cupy' 没有属性 'gradient'
- java - 带有微服务和 Docker-Compose 错误的 Spring Cloud Stream Kafka
- python - “值”对象没有属性“保存”
- clang-format - 我可以禁用 Clang 格式中某些宏的所有调用的格式吗?
- sql - 如何在存储过程中从 VARIABLE 表中选择数据
- mysql - mySQL 选择随时间变化 X% 的价格记录
- java - 无法使用本地 JDBC 应用程序连接到安装在 aws 中的 mysql
- sockets - 在 Windows 上使用来自 GNU Emacs 的 Emacs Lisp 打开 UDP / 数据报套接字