【问题标题】:React Native - component callback animates a view first time but not on subsequent callsReact Native - 组件回调第一次为视图设置动画,但在后续调用中不设置动画
【发布时间】:2021-09-25 11:40:04
【问题描述】:

我有一个动画,它是通过发送到 render() 中的组件的回调函数触发的。动画只是一些从屏幕右边缘外侧穿过屏幕并离开左侧的文本。第一次触发回调时,它运行良好,但在随后的回调中什么都看不到,也没有错误。相关代码如下:

     import { Animated, Easing....} from 'react-native';
        
        class Play extends Component {
          constructor() {
            super();
            this.state = {currSectName:"Intro",  
            sectNameXcord: new Animated.Value(Dimensions.get('window').width),....}
          }
    
         sectNameTraverse = (newSect) =>{
            this.state.currSectName = newSect;
            this.state.sectNameXcord = new Animated.Value(Dimensions.get('window').width);
    
            //run the animation
            Animated.timing(
              this.state.sectNameXcord,
              {
                toValue: -320,
                duration: 3000, // the duration of the animation
                easing: Easing.linear, // the style of animation 
                useNativeDriver: true
              }
            ).start((res)=>{
                console.log(res);
            }); 
          } 
    
          render() {
               return (
                 <>
                  <Animated.View style={{position: 'absolute',top:100,
transform: [{translateX: this.state.sectNameXcord }]}}>
                    <Text style={{ color:"white",opacity:0.5,fontStyle: 'italic',fontWeight: 'bold',fontSize:99}}>
                     {this.state.currSectName}
                    </Text>
                  </Animated.View>
    
                 <Player
                 sectionChange={(newSect) => {this.sectNameTraverse(newSect)}}
                 />
          }

在随后的回调中,以下情况为真:

  • 状态变量已更新并为下一个动画更正
  • Animated.timing().start() 的回调在持续时间后显示 {"finished": true} 就好像它已正确执行但屏幕上没有显示任何内容
  • 不会引发错误

我猜它可能与实例/绑定有关,但我还不够好 使用 React Native 来修复它。坚持了 2 天,真的需要一些帮助。

非常感谢。

【问题讨论】:

    标签: react-native animation callback


    【解决方案1】:

    你不应该改变状态。您应该使用“setState”来更新状态。

      sectNameTraverse = (newSect) => {
        this.setState(
          { 
            currSectName:newSect,
            sectNameXcord: new Animated.Value(Dimensions.get('window').width)
            },
          () => {
            //run the animation
            Animated.timing(this.state.sectNameXcord, {
              toValue: -320,
              duration: 3000, // the duration of the animation
              easing: Easing.linear, // the style of animation
              useNativeDriver: true,
            }).start((res) => {
              console.log(res);
            });
          }
        );
      };
    

    这是我创建的snack

    【讨论】:

    • 谢谢。它现在抛出“警告:在现有状态转换期间无法更新(例如在render 内)。渲染方法应该是道具和状态的纯函数。”但我会将其标记为已解决,因为动画确实符合要求。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 2021-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多