首页 > 解决方案 > 如何使用状态动态更改 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

解决方案


我遇到了同样的问题,并通过使用来自 react-native-reanimated 的 Animated.View 解决了它。(标准 react-native 包中的 Animated.View 也可能有效,但我没有检查)。我不需要使用 Animated 值,我仍然只使用状态中的实际值,并且它起作用了。


推荐阅读