我安裝了這個react-native-really-awesome-button包,因為它有一些非常棒的按鈕。
不幸的是,onPress處理程式似乎沒有按預期作業。
這是一個可重現的演示:https ://snack.expo.dev/@anshnanda/awesomebutton-not-working
您可以清楚地看到該onPress函式僅使用初始狀態,并沒有更新為新狀態。
很明顯,AwesomeButton 只是使用它的初始狀態值,num這讓我認為該函式是用useMemoor包裝的useCallback(可能存在錯誤),但是,通過挖掘源代碼,我找不到發生這種情況的原因。
我嘗試使用onPressInandonPressOut并且那些似乎作業正常,除了 UX 顯然更糟,因為用戶沒有看到我下載的流暢影片react-native-really-awesome-button。
uj5u.com熱心網友回復:
您似乎在要求確認這是 中的錯誤/問題AwesomeButton,我同意這是。
onPress回呼存盤在 React ref: ( source )
const debouncedPress = useRef( debouncedPressTime ? debounce( (animateProgressEnd: (callback?: any) => void) => onPress(animateProgressEnd), // <-- here debouncedPressTime, { trailing: false, leading: true, } ) : onPress // <-- here );
debouncedPress在處理程式中呼叫press:(source)
const press = () => { actioned.current = true; if (progressing.current === true) { return; } if (progress === true) { requestAnimationFrame(startProgress); } debouncedPress.current(animateProgressEnd); // <-- here };
press由handlePressOut回呼呼叫:(source)
它animateProgressEnd是呼叫傳遞onPress函式(debouncedPress)的處理程式:(source)
const animateProgressEnd = (callback: any) => { // <-- your callback if (progress !== true) { return; } if (timeout?.current) { clearTimeout(timeout.current); } requestAnimationFrame(() => { animateTiming({ variable: animatedLoading, toValue: 1, }).start(() => { Animated.parallel([ animateElastic({ variable: textOpacity, toValue: 1, }), animateElastic({ variable: activityOpacity, toValue: 0, }), animateTiming({ variable: loadingOpacity, toValue: 0, delay: 100, }), ]).start(() => { animateRelease(() => { progressing.current = false; callback && callback(); // <-- called here onProgressEnd && onProgressEnd(); }); }); }); }); };
所以是的,React refdebouncedPress永遠不會更新以保存您傳遞的onPress回呼處理程式的更新實體。
為了解決這個問題,您可以在代碼中使用 React ref 來快取num狀態并在printCurrNum處理程式中參考它。
例子:
function App() {
const [num, setNum] = React.useState(0);
const [currentValue, setCurrentValue] = React.useState(0);
const numRef = React.useRef(num); // <-- ref to cache num state
React.useEffect(() => { // <-- effect to update cache
numRef.current = num;
}, [num]);
const increment = () => {
setNum((num) => num 1);
};
const printCurrNum = () => {
console.log(numRef.current); // <-- reference current value
setCurrentValue(numRef.current); // <-- reference current value
};
return (
<View style={styles.container}>
<Text>Current value according to AwesomeButton: {currentValue}</Text>
<Text>{num}</Text>
<AwesomeButton onPress={printCurrNum}>
Update current value with Awesome Button
</AwesomeButton>
<Button title="Increment" onPress={increment} />
<Button
title="Update current value with native button"
onPress={printCurrNum}
/>
</View>
);
}
https://snack.expo.dev/@drew.w.reese/awesomebutton-not-working
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/526842.html
