我正在构建一个自定义视图,它将根据设备方向旋转其内容。这个应用程序的方向锁定为肖像,我只想旋转一个单一的视图。它获取当前设备方向,更新状态,然后使用更新的style={{transform: [{rotate: 'xxxdeg'}]}}呈现新组件。
我使用react-native-orientation-locker来检测方向的变化。
视图在第一次呈现时正确地呈现旋转。例如,如果屏幕在设备旋转时加载,它将呈现视图旋转。但是,当改变设备或模拟器的方向时,视图不会旋转。它保持锁定在它被初始化的rotate值。
似乎对transform rotate值的更新不会改变旋转。我已经验证了在呈现过程中是否存在新的rotate值。我已经验证了方向更改是否正确地更新了状态。但是,当方向发生变化时,视图在UI中永远不会旋转。就好像React本机在呈现过程中没有接收到对rotate值的更改。
我希望对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;发布于 2021-04-28 06:01:43
这是一个错误,因为当rotate的值更新时,旋转应该会改变。解决方法之一是将View的key属性设置为旋转值。
例如:
return (
<View
key={rotate} // <~~~ fix!
style={{transform: [{rotate}]}}
>
{props.children}
</View>
)我找到了这个解决方案,这里。
https://stackoverflow.com/questions/58684624
复制相似问题