如何解决如何动态改变状态的React Native??
开发过程中遇到如何动态改变状态的React Native?的问题如何解决?下面主要结合日常开发的经验,给出你关于如何动态改变状态的React Native?的解决方法建议,希望对你解决如何动态改变状态的React Native?有所启发或帮助;问题描述
我正在构建一个自定义视图,该视图将根据设备方向旋转其内容。这个应用程式的方向锁定为纵向,我只想旋转一个视图。它获取当前设备方向,更新状态,然后使用更新后的style={{transform: [{rotate: 'xxxdeg'}]}}
渲染新组件。
我正在使用react-native-orientation-locker
来检测方向变化。
视图渲染在第一个渲染上正确旋转。例如,如果在旋转设备时加载屏幕,它将使视图旋转。但是在更改设备或模拟器的方向时,视图不会旋转。它保持锁定在初始化时的rotate
值。
似乎对transform
rotate
值的更新不会改变旋转。我已验证在渲染过程中是否存在新的rotate
值。我已验证方向更改正确更新了状态。但是,当方向改变时,视图永远不会在UI中旋转。就像React Native在渲染期间没有对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;
尚未找到解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)