reactjs - 变量没有采用 Reactjs 中变量的初始值
问题描述
我正在 reactjs 中制作图像查看器。实际上,我希望当用户单击旋转图标时,图像会旋转约 90 度。一切进展顺利,但主要问题是当我单击任何图像并旋转它并关闭它,然后如果我打开其他图像,它会采用以前的旋转值,但在我初始化时它必须为零。
class GalleryModal extends React.Component {
constructor(props) {
super(props);
this.state = {
rotation: 0
};
this.rotate = this.rotate.bind(this);
this.fullScreen = this.fullScreen.bind(this);
}
render() {
const { rotation } = this.state;
if (this.props.isOpen === false) {
return null;
}
return (
<div className="modal-overlay" name={this.props.name}>
<div className="modal-body" id="image_container">
<img
className="center_image"
id="image"
src={this.props.src}
style={{ transform: `rotate(${rotation}deg)` }}
/>
<a href="#" className="fullscreen button" onClick={this.fullScreen}>
<i className="fas fa-compress-arrows-alt"></i>
</a>
<a href="#" className="button" onClick={() => this.rotate()}>
<i className="fas fa-sync-alt" />
</a>
<a href="#" className="button" onClick={this.props.onPrev}>
<i className="fas fa-angle-left" />
</a>
<a href="#" className="button" onClick={this.props.onNext}>
<i className="fas fa-angle-right" />
</a>
<a
className="modal-close"
href="#"
onClick={this.props.onClick}
>
<span className="fa fa-times" />
</a>
</div>
</div>
);
}
rotate() {
let newRotation = this.state.rotation + 90;
if (newRotation >= 360) {
newRotation = -360;
}
this.setState({
rotation: newRotation
});
}
fullScreen() {
let elem = document.getElementById("image_container");
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.mozRequestFullScreen) {
/* Firefox */
elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
/* Chrome, Safari & Opera */
elem.webkitRequestFullscreen();
} else if (elem.msRequestFullscreen) {
/* IE/Edge */
elem.msRequestFullscreen();
}
}
}
Demo here这是我尝试过的,但是当我单击另一个图像或下一个/上一个图标时,它会采用以前的值,但rotation
正如我声明的那样,它必须为零rotation:0
。我不知道旋转错误是从哪里引起的,因为我认为我做对了。你能告诉我我做错了什么以及如何解决吗????
解决方案
问题是,当您设置状态有 时rotation: 0
,您正在修改Gallery
组件的状态;因此,当您打开模型时,Gallery
组件将自己的this.state.rotation
变量设置为0
.
相反,用于显示图像的旋转是GalleryModal
Component 中的旋转,永远不会再设置为0
。
一种解决方案可能是将this.state.rotation
变量从Gallery
组件传递到GalleryModal
组件。
那里是你的小提琴固定:https ://jsfiddle.net/3hywna07/
此外,在第 61 行,而不是写:
<a href="#" className="button" onClick={() => this.props.rotate()}>
写吧:
<a href="#" className="button" onClick={this.props.rotate}>
应该避免在方法中使用箭头函数,render()
因为它会导致每次render()
执行方法时都创建函数。
推荐阅读
- android - 有没有办法让我们按钮 onclick 监听器在 android 上打开导航抽屉
- php - 如何在几天的数组中查询每一天的数据库laravel
- mysql - 这是一个 MySQL 错误吗?
- python - 无监督学习、Python、文本聚类
- react-native - React Native 语义问题:“MethodDescriptor”的重新定义
- sql - 连接 2 个 PostgreSQL 表
- python - 如何从特定时间范围内的股票报价数据中保存数据
- java - 我想要一个字符打印 int 次数
- java - 运动事件未出现在 Logcat 上
- javascript - 循环通过图像数组作为轮播