我想在 fadeOut 函式結束時更改一個值。
我有以下功能:
const fadeOut = (duration: number = 300) => {
Animated.timing(
opacity,
{
toValue: 0,
duration,
useNativeDriver: true
}
).start();
}
我這樣稱呼它:
const fadeOutScreen = () => {
fadeOut(1000);
// The value would be true when the fadeOut is over
setHide(true);
}
但是值在操作結束之前發生了變化。
我該如何解決這個問題?
uj5u.com熱心網友回復:
使其異步:
這是檔案
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
}
};
uj5u.com熱心網友回復:
影片是異步運行的,但是fadeOutScreen影片啟動后函式會繼續同步執行。
Animated.start()但是,它會接受一個在影片完成后呼叫的回呼,因此您可以這樣做:
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);
}
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/433663.html
標籤:javascript 反应 打字稿 反应式
