在react-native中,如何将View的背景颜色更改为另一种颜色,然后淡出?

时间:2019-07-23 07:24:17

标签: react-native animation view

我想将“视图”更改为深蓝色,然后逐渐淡出至正常颜色(又称白色)。

这怎么办?

1 个答案:

答案 0 :(得分:0)

您可以通过本机使用动画。  这是一个示例代码,可满足您的需求

import * as React from "react";
import { Text, View, StyleSheet, Animated } from "react-native";

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      colorAnimation: new Animated.Value(0)
    };
  }

  componentDidMount() {
    const { colorAnimation } = this.state;

    {
      /* Change Color To blue */
    }
    Animated.timing(colorAnimation, {
      toValue: 255,
      duration: 1000 //Animation Duration
    }).start();

    {
      /*  After 1 second change color back to white */
    }

    setInterval(() => {
      Animated.timing(colorAnimation, {
        toValue: 0,
        duration: 3000 //Animation Duration
      }).start();
    }, 1000);
  }

  render() {
    const interpolatedColor = this.state.colorAnimation.interpolate({
      inputRange: [0, 255],
      outputRange: ["rgb(255,255,255)", "rgb(0, 0, 139)"]
    });
    return (
      <Animated.View
        style={[styles.container, { backgroundColor: interpolatedColor }]}
      ></Animated.View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    padding: 8
  }
});

You can view the demo here.