反应本机状态更改转换

时间:2018-05-30 10:55:25

标签: animation react-native transitions

在状态变化中为组件设置动画的最佳模式是什么?

例如,我有一个元素列表,并点击一个我希望它消失的元素和他下面的元素来“起床”。填补缺失的空间

如何使过渡顺利进行?

2 个答案:

答案 0 :(得分:1)

React-natives拥有animated API的效果非常好。

基本上你有一个状态值,你可以用样式道具连接,并随着时间的推移改变这个值。 (例如,链接)

对于流畅的动画,请使用usenativedriver(并非总是可行),并确保您在模拟/真实设备中没有调试器运行

  

编辑:2018-05-31

这是我如何使用它的一个例子。可能存在其他方式

import { Animated, Text} from 'react-native';

class ShowCaseAnimation extends Component {

  state = { 
    animations: {
      height: new Animated.Value(0),
      fade: new Animated.Value(0),
    }
  }

  componentDidMount() {
    const { height, fade } = this.state.animations;
    if (this.props.animate) {
      doneAnimation({ height, fade }).start(() => {
        // Do stuff after animations
      });
    }
  }

  render() {
    const { animations } = this.state; 
    return (
      <Animated.View 
        style={{
          height: animate? animations.height : 300, 
          opacity: animate? animations.fade: 1,
          // other styling 
        }}
      >
        <Text> All your base are belong to us </Text>
      </Animated.View>
    );
  }
}

* doneAnimation:*

import { Animated, Easing } from 'react-native';

export const doneAnimation = ({ height, fade }) => Animated.parallel([
  Animated.timing(height, {
    toValue: 300,
    easing: Easing.elastic(),
    duration: 500,
    delay: 1500,
  }),
  Animated.timing(fade, {
    toValue: 1,
    easing: Easing.ease,
    duration: 1000,
    delay: 1500,
  }),
]);

export default doneAnimation;

doneAnimation 将更改状态并执行所描述的动画。

答案 1 :(得分:0)

这是您可以在功能组件中的状态变化时触发动画的方法。

假设您有一个可以通过onPress更改状态的按钮:

<Button title="toggle" onPress={() => setValue(!Value)} />

然后您可以在Value的useEffect中触发动画 依赖项数组中的变化:

const [Value, setValue] = useState(true);

useEffect(() => {
    // Input your animation here
    // ...
  }, [Value]);

相关问题