【问题标题】:How can I implement animation in my flatlist?如何在我的平面列表中实现动画?
【发布时间】:2019-01-11 07:34:01
【问题描述】:

我在我的 rn 项目中使用 Flatlist,当我将新数据推送到我的 flatlist 时,我的项目 1 将自动从位置 A 移动到位置 B。但我的问题是我不希望它只是改变位置,我想使用动画来移动我的项目(从位置 A 到位置 B)。我该如何实施?谢谢!

请查看以下链接中的演示图片和视频: https://photos.app.goo.gl/WypswNyA38A2EAPQA https://photos.app.goo.gl/Ev1RYMduDj7mxrHn7

【问题讨论】:

    标签: react-native animation react-native-flatlist


    【解决方案1】:

    您可以使用Animated 组件来制作动画。根据您附加的视频,两步动画开始发挥作用,一个将项目向上推到列表中,另一个增加列表项的不透明度。一个简单的方法是添加高度为0 的列表项,并使用动画将高度增加到所需的高度,这将完成第一步。第一步完成后,控制opacity0变为1

    接下来,您需要在列表项添加到列表时启动动画,componentDidMount 是这样做的正确位置。请考虑执行上述步骤的以下组件。

    import React from 'react';
    import { Animated } from 'react-native';
    
    class AnimatedListItem extends React.Component {
      constructor(...props) {
        super(...props);
        this.state = {
          height: new Animated.Value(0),
          opacity: new Animated.Value(0)
        };
      }
    
      componentDidMount() {
        Animated.sequence([
          Animated.timing(
            this.state.height,
            {
              toValue: this.props.height,
              duration: this.props.duration || 1000
            }
          ),
          Animated.timing(
            this.state.opacity,
            {
              toValue: 1,
              duration: this.props.duration || 1000
            }
          )
        ]).start();
      }
    
      render() {
        const { height, opacity } = this.state;
        return (
          <Animated.View
            style={{
              ...this.props.style,
              height: height,
              opacity: opacity
            }}
          >
            {this.props.children}
          </Animated.View>
        );
      }
    }
    
    export default AnimatedListItem;

    在上面的sn-p中,两个动画被传递给Animated.sequence([...])方法一个接一个地动画。

    您现在可以在renderItem 方法中使用上述组件

    renderItem = () => {
      return (
        <AnimatedListItem height={50} duration={800} style={...}>
          /* render actual component here */
        </AnimatedListItem>
      );
    }
    

    希望这会有所帮助!

    注意:这是实现您正在寻找的内容的最低限度示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-30
      相关资源
      最近更新 更多