ReactJS 图片高度动态计算:根据宽度设置一半高度
可以通过在 React 组件中使用 state 来计算并更新图片的高度,使其始终保持为宽度的一半。以下是一个示例代码:
import React, { Component } from 'react';
class ImgComponent extends Component {
constructor(props) {
super(props);
this.state = {
width: 0,
height: 0,
};
this.handleResize = this.handleResize.bind(this);
}
componentDidMount() {
this.handleResize();
window.addEventListener('resize', this.handleResize);
}
componentWillUnmount() {
window.removeEventListener('resize', this.handleResize);
}
handleResize() {
const width = this.imgRef.clientWidth;
const height = width / 2;
this.setState({ width, height });
}
render() {
const { src } = this.props;
const { width, height } = this.state;
return (
<img
ref={(ref) => { this.imgRef = ref; }}
src={src}
style={{ width: `${width}px`, height: `${height}px` }}
/>
);
}
}
export default ImgComponent;
代码解释:
- 使用 state 保存宽度和高度: 在组件的 state 中保存图片的宽度和高度,以便在组件渲染时使用。
- 在 componentDidMount 中计算初始值和添加监听器: 当组件挂载到 DOM 时,使用
componentDidMount方法计算图片的初始宽度和高度,并添加窗口 resize 事件监听器,以便在窗口大小改变时重新计算图片高度。 - 在 componentWillUnmount 中移除监听器: 当组件卸载时,使用
componentWillUnmount方法移除窗口 resize 事件监听器,以防止内存泄漏。 - 使用 ref 获取图片元素的引用: 使用
ref属性获取图片元素的引用,以便在handleResize方法中获取图片的实际宽度。 - 在 handleResize 方法中计算高度: 在
handleResize方法中获取图片的宽度,并将其除以 2 来计算高度,最后更新 state 中的高度值。 - 在 render 方法中设置宽度和高度: 在
render方法中,将图片的宽度和高度设置为 state 中保存的值。
通过以上步骤,可以实现图片高度始终保持为宽度的二分之一,并根据窗口大小的变化进行动态调整。
原文地址: https://www.cveoy.top/t/topic/oA2l 著作权归作者所有。请勿转载和采集!