React-Native:布局动画

7
我正在使用react-native的LayoutAnimation来实现一个自定义开关组件。

enter image description here

我正在使用LayoutAnimation来制作圆形的动画移动,如下所示:
componentWillUpdate() {
  let switchAnimation = {
    duration: 250,
     update: {
       type: LayoutAnimation.Types.linear,
       property: LayoutAnimation.Properties.opacity,
     },
  };
  LayoutAnimation.configureNext(switchAnimation);
}

开关是一个独立的组件。它通过接收属性来使用CSS(justifyContent flex-start或flex-end)将圆圈设置为左侧或右侧。
问题在于,当开关改变值时,其他组件也会改变:即当按下开关时:
1)开关改变
2)图标改变
3)一些文本改变
以上所有内容都有动画效果。我希望减少动画对开关的影响。
更新:我已尝试使用Animated API,但似乎不支持动画化flex属性。真的没有人广泛使用Animated API吗?

LayoutAnimation在这里不是正确的方式。考虑使用Animated API https://facebook.github.io/react-native/docs/animations.html - agenthunt
文档中的示例使用了组件状态。在我的情况下,这将如何工作?我应该将一个属性映射到一个状态变量并从那里创建动画吗? - Gilbert Nwaiwu
我已经更新了我的答案,并提供了一个示例,其中包括使用flex属性与动画API。 - Beau Smith
2个回答

1

LayoutAnimation在幕后做了很多工作。除非你愿意查看源代码,否则你可以设置和改变边距值来移动容器中的圆圈。你可以在组件内部进行所有计算,并将一些样式公开为props。


谢谢。看起来似乎是唯一可行的解决方案。 - Gilbert Nwaiwu

-2

此问题是由于使用了错误的动画解决方案导致的。

要为特定元素添加动画,请使用Animated API,而不是LayoutAnimation API

了解有关动画指南中差异的更多信息。

在尝试使用值范围为0到1的flex属性来动画化进度条时,我学到了这种差异。

以下是一些示例代码,已编辑以删除与项目无关的内容...

import React from 'react'
import { Animated, View } from 'react-native'
const progressStyles = {
  height: 10,
  backgroundColor: 'blue',
}
class PasswordStrengthMeter extends React.Component {
  state = {
    width: new Animated.Value(0), // value in the range 0–1
  }
  componentWillReceiveProps(nextProps) {
    if (nextProps.score !== this.props.score) {
      Animated.timing(this.state.width, {
        toValue: nextProps.score / 4, // score will be a value between 0-4
        duration: 500,
      }).start()
    }
  }
  render() {
    return (
      <View>
        <Animated.View
          style={[
            progressStyles,
            {
              flex: this.state.width, // value in the range 01
            },
          ]}
        />
      </View>
    )
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接