react-native - 如何使用状态动态更改 React Native 转换?
问题描述
我正在构建一个自定义视图,它将根据设备方向旋转其内容。这个应用程序的方向锁定为纵向,我只想旋转一个视图。它获取当前设备方向,更新状态,然后使用更新的style={{transform: [{rotate: 'xxxdeg'}]}}
.
我react-native-orientation-locker
用来检测方向变化。
视图在第一次渲染时正确旋转。例如,如果屏幕在设备旋转时加载,它将渲染视图旋转。但是在更改设备或模拟器的方向时,视图不会旋转。它保持锁定在rotate
初始化时的值。
似乎对transform
rotate
值的更新不会改变旋转。我已经验证rotate
在渲染过程中存在新值。我已经验证方向更改正确地更新了状态。但是当方向改变时,视图永远不会在 UI 中旋转。就好像 React Nativerotate
在渲染期间没有注意到值的变化。
我希望对rotate
值的更新会相应地轮换View
,但情况似乎并非如此。有没有其他方法可以做到这一点,或者我在这段代码中有错误吗?
编辑:它是否需要rotate
成为一个Animated
值?
import React, {useState, useEffect} from 'react';
import {View} from 'react-native';
import Orientation from 'react-native-orientation-locker';
const RotateView = props => {
const getRotation = newOrientation => {
switch (newOrientation) {
case 'LANDSCAPE-LEFT':
return '90deg';
case 'LANDSCAPE-RIGHT':
return '-90deg';
default:
return '0deg';
}
};
const [orientation, setOrientation] = useState(
// set orientation to the initial device orientation
Orientation.getInitialOrientation(),
);
const [rotate, setRotate] = useState(
// set rotation to the initial rotation value (xxdeg)
getRotation(Orientation.getInitialOrientation()),
);
useEffect(() => {
// Set up listeners for device orientation changes
Orientation.addDeviceOrientationListener(setOrientation);
return () => Orientation.removeDeviceOrientationListener(setOrientation);
}, []);
useEffect(() => {
// when orientation changes, update the rotation
setRotate(getRotation(orientation));
}, [orientation]);
// render the view with the current rotation value
return (
<View style={{transform: [{rotate}]}}>
{props.children}
</View>
);
};
export default RotateView;
解决方案
我遇到了同样的问题,并通过使用来自 react-native-reanimated 的 Animated.View 解决了它。(标准 react-native 包中的 Animated.View 也可能有效,但我没有检查)。我不需要使用 Animated 值,我仍然只使用状态中的实际值,并且它起作用了。
推荐阅读
- c# - 如何复制带有链接的richtextbox内容?
- angular - 动态复选框 - formGroup 中的 FormGroup 包含 formArray
- javascript - JavaScript:为什么“for in”循环从 __proto__ 中选择变量?
- excel - 比较两列的颜色
- klepto - klepto dir_archive 的密钥?
- css - 如何将 URL 图像添加为 scss 变量
- c++ - 如何在 LabVIEW 的 DLL 中打开 OpenCV 结构化边缘检测器的模型文件?
- docker - 如何运行使用 go binary 创建的 docker 容器?
- selenium-webdriver - 无法使用 Selenium Webdriver 向下滚动
- r - 编写 dplyr 函数以传递给 group_map