当组件的属性更改时重新启动“React Native动画”

uyhoqukh  于 2023-02-25  发布在  React
关注(0)|答案(1)|浏览(113)

我有一个呈现通知文本的React Native组件。我希望文本在一个小的延迟后淡入淡出。当设置新的通知文本时,我希望重新启动相同的动画。
下面的代码:

export default function Notification({ notification }) {
    if (!notification) {
        return null;
    }

    const [fadeAnimation] = useState(new Animated.Value(0));

    useEffect(() => {
        Animated.sequence([
            Animated.timing(fadeAnimation, {
                toValue: 1,
                duration: 500,
                useNativeDriver: true,
            }),
            Animated.delay(3000),
            Animated.timing(fadeAnimation, {
                toValue: 0,
                duration: 500,
                useNativeDriver: true,
            })]).start()
    }, []);

    return (
        <Animated.View style={{ opacity: fadeAnimation, }}>
            <View style={styles.notificaton}>
                <Text style={styles.text}>{notification}</Text>
            </View>
        </Animated.View >
    )
}

我读到我应该能够再次使用setValue(0)重置动画,但是我不知道何时何地调用它。

7lrncoxx

7lrncoxx1#

"为我工作"

import React, { Component } from 'react';
import { Animated, View } from 'react-native';

class Testing extends Component {
  constructor(props) {
    super(props);
    this.animatedValue = new Animated.Value(0);
  }

  componentDidUpdate(prevProps) {
    if (prevProps.myProp !== this.props.myProp) {
      this.startAnimation();
    }
  }

  startAnimation() {
    this.animatedValue.setValue(0);
    Animated.timing(this.animatedValue, {
      toValue: 1,
      duration: 1000,
      useNativeDriver: true,
    }).start();
  }

  render() {
    const { myProp } = this.props;
    const opacity = this.animatedValue.interpolate({
      inputRange: [0, 1],
      outputRange: [0, 1],
    });

    return (
      <View>
        <Animated.Text style={{ opacity }}>
          My prop val : {myProp}
        </Animated.Text>
      </View>
    );
  }
}

export default Testing;

相关问题