使用React Native Animated淡入和淡出元素

pan*_*149 4 react-native

我是刚接触原生动画功能的新手。我希望使用它来淡入和淡出按钮时的元素。下面的代码可在页面加载时在元素中淡入淡出,但是淡出该按钮的按钮并不会像我期望的那样使其淡出。有人可以解释我在做什么错。谢谢。

class FadeComponent extends Component {

  constructor(props) {
    super(props)
    this.state = {
      fadeAnim: new Animated.Value(0),  // Initial value for opacity: 0
    }
    this.fadeOut = this.fadeOut.bind(this);
  }

  componentDidMount() {
    Animated.timing(          // Animate over time
      this.state.fadeAnim,    // The animated value to drive
      {
        toValue: 1,           // Animate to opacity: 1 (opaque)
        duration: 2000,       // 2000ms
      }
    ).start();                // Starts the animation
  }

  fadeOut(){
    this.setState({fadeAnim: new Animated.Value(1)})
    Animated.timing(          // Animate over time
      this.state.fadeAnim, // The animated value to drive
      {
        toValue: 0,           // Animate to opacity: 1 (opaque)
        duration: 2000,       // 2000ms
      }
    ).start();                // Starts the animation
  }

  render() {
    let { fadeAnim } = this.state;

    return (
      <View style = {{ backgroundColor: '#1a8cff', marginTop: 100 }}>

        <Animated.View style={{ ...this.props.style, opacity: fadeAnim }} >
          {this.props.children}
          <View style = {{ backgroundColor: '#000000', height: 50, width: 50 }}>
          </View>
        </Animated.View>

        <TouchableOpacity onPress={this.fadeOut} >
          <Text style={{ color: 'white', textDecorationLine: 'underline', marginTop: 10 }}>
          fade out
          </Text>
        </TouchableOpacity>

      </View>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

Kie*_*nLV 7

因为函数setState是异步的。这应该可以解决您的问题:

this.setState({ fadeAnim: new Animated.Value(1) },
  () => {
    Animated.timing(          // Animate over time
      this.state.fadeAnim, // The animated value to drive
      {
        toValue: 0,           // Animate to opacity: 1 (opaque)
        duration: 2000,       // 2000ms
      }
    ).start();
  })
Run Code Online (Sandbox Code Playgroud)

  • 也许将其设置为答案? (2认同)