首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何用状态动态地改变本机变换?

如何用状态动态地改变本机变换?
EN

Stack Overflow用户
提问于 2019-11-03 21:05:14
回答 4查看 2.5K关注 0票数 4

我正在构建一个自定义视图,它将根据设备方向旋转其内容。这个应用程序的方向锁定为肖像,我只想旋转一个单一的视图。它获取当前设备方向,更新状态,然后使用更新的style={{transform: [{rotate: 'xxxdeg'}]}}呈现新组件。

我使用react-native-orientation-locker来检测方向的变化。

视图在第一次呈现时正确地呈现旋转。例如,如果屏幕在设备旋转时加载,它将呈现视图旋转。但是,当改变设备或模拟器的方向时,视图不会旋转。它保持锁定在它被初始化的rotate值。

似乎对transform rotate值的更新不会改变旋转。我已经验证了在呈现过程中是否存在新的rotate值。我已经验证了方向更改是否正确地更新了状态。但是,当方向发生变化时,视图在UI中永远不会旋转。就好像React本机在呈现过程中没有接收到对rotate值的更改。

我希望对rotate值的更新会相应地旋转View,但情况似乎并非如此。还有其他方法来完成这个任务吗?还是我在这段代码中有错误?

编辑:rotate是否需要成为一个Animated值?

代码语言:javascript
复制
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;
EN

Stack Overflow用户

发布于 2021-04-28 06:01:43

这是一个错误,因为当rotate的值更新时,旋转应该会改变。解决方法之一是将View的key属性设置为旋转值。

例如:

代码语言:javascript
复制
return (
  <View
    key={rotate} // <~~~ fix!
    style={{transform: [{rotate}]}}
  >
    {props.children}
  </View>
)

我找到了这个解决方案,这里

票数 0
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58684624

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档