如何使用react-native动画在一段时间后自动淡出文本

Kis*_*ore 7 animation react-native

通过使用以下代码,我可以淡入一些文本,

class AnimatedClass extends Component {
   constructor(props) {
      super(props);

      this.state = {fadeIn: new Animated.Value(0),
                    fadeOut: new Animated.Value(1),
                   };
   }

   fadeIn() {
     this.state.fadeIn.setValue(0)                  
     Animated.timing(
       this.state.fadeIn,           
       {
         toValue: 1,                   
         duration: 3000,              
       }
     ).start(() => this.fadeOut());                        
  }

  fadeOut() {
    this.state.fadeOut.setValue(1)
    Animated.timing(                  
       this.state.fadeOut,            
       {
         toValue: 0,                   
         duration: 3000,              
       }
    ).start();                        
  }

  render() {
    return(
       <View style={{flex: 1, backgroundColor: '#efefef'}}>
           <TouchableOpacity 
               onPress={() => this.fadeIn()} 
               style={Styles.submitButtonStyle}
               activeOpacity={0.5}
           >
               <Text style={Styles.submitTextStyle}>Submit</Text>
           </TouchableOpacity>

           <Animated.View                 
              style={{opacity: this.state.fadeIn}}
           >
              <View style={Styles.textContainer}>
                <Text style={{fontSize: 20, textAlign: 'center'}}>Your order has been submitted</Text>
             </View>
           </Animated.View>
       </View>
   );

 }
}
Run Code Online (Sandbox Code Playgroud)

但是,Anyway Text在一段时间后不会自动消失.事实上,我会在文本应该淡出多少秒后设置时间.但它不起作用.

任何帮助表示赞赏.提前致谢.

Mat*_*K14 9

您将不透明度基于this.state.fadeIn但this.state.fadeOut在您的fadeOut().

尝试:

fadeOut() {
    Animated.timing(                  
       this.state.fadeIn,            
       {
         toValue: 0,                   
         duration: 3000,              
       }
    ).start();                        
  }
Run Code Online (Sandbox Code Playgroud)

并且可能将变量名称更改为 justfadeValue或更清晰的内容,以供将来使用。

  • 成功了,谢谢。但是我不明白`this.state.fadeIn.setValue(1)`的目的。你能让我知道吗? (2认同)