简体   繁体   English

如何等待淡出 function 结束?

[英]How to wait for an fadeout function to end?

I would like to change a value when a fadeOut function is over.我想在 fadeOut function 结束时更改一个值。

I have the following function:我有以下 function:

    const fadeOut = (duration: number = 300) => {
        Animated.timing(
            opacity,
            {
                toValue: 0,
                duration,
                useNativeDriver: true
            }
        ).start();
    }

And I call it this way:我这样称呼它:

    const fadeOutScreen = () => {
        fadeOut(1000);

        // The value would be true when the fadeOut is over
        setHide(true);
    }

But the value is changed before the operation ends.但是在操作结束之前该值已更改。

How can I solve this?我该如何解决这个问题?

Make it async:使其异步:

Here are the docs 是文档

TS Playground TS游乐场

const fadeOut = (duration: number = 300) => new Promise<boolean>(resolve => {
  Animated.timing(
    opacity,
    {
      toValue: 0,
      duration,
      useNativeDriver: true,
    }
  ).start(({finished}) => resolve(finished));
});

const fadeOutScreen = async () => {
  const finished = await fadeOut(1000);
  if (finished) setHide(true);
  else {
    // animation was interrupted
  }
};

The animation runs asynchronously, but the fadeOutScreen function will continue to execute synchronously after the animation is started. animation异步运行,但是fadeOutScreen function会在animation启动后继续同步执行。

Animated.start() , however, takes a callback that is called once the animation is finished, so you can do it like this:但是, Animated.start()会在 animation 完成后调用一个回调,因此您可以这样做:

const fadeOut = (duration: number = 300, cb?: (boolean) => void) => {
    Animated.timing(
        opacity,
        {
            toValue: 0,
            duration,
            useNativeDriver: true
        }
    ).start(
      //vvvvvvvv--- This tells whether the animation has finished or stopped
      ({finished}) => cb?.(finished)
      //                ^^--- Only call callback if present (new syntax)
    );
}
const fadeOutScreen = () => {
    fadeOut(
        1000, 
        finished => {
            if(finished)
                setHide(true);
        }
    );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM