我是 React Native 的新手,我正在構建我的第一個應用程式。我有一個按鈕組件,按下時會執行某些操作,而按住時會執行相同但重復的操作。為了實作這一點,我構建了一個簡單的邏輯,但我無法讓它正常作業,因為當我按住按鈕時它會做它應該做的事情,但控制臺說:
“請給這個組件附加一個方法”
當我松開按鈕時會顯示該訊息,因此我認為問題出在 onPressOut 中。
這是代碼,對代碼中的西班牙語感到抱歉:c
import { View, Text, StyleSheet } from "react-native";
import { Button } from "react-native-elements";
interface INTERFACE {
accionMenos: () => void;
accionMas: () => void;
texto: string;
titleBotonMenos: string;
titleBotonMas: string;
}
const BotonTextoBoton = ({
accionMenos,
accionMas,
texto,
titleBotonMenos,
titleBotonMas,
}: INTERFACE) => {
let timer: NodeJS.Timeout;
function addTimer(action: () => void) {
action();
timer = setTimeout(() => {
addTimer(action);
}, 100);
}
function eraseTimer() {
clearTimeout(timer);
}
return (
<View style={styles.viewContainer}>
<View style={{ width: "15%", backgroundColor: "red" }}>
<Button
onPressIn={() => addTimer(accionMenos)}
onPressOut={eraseTimer}
title={titleBotonMenos}
/>
</View>
<Text style={{ margin: 3, fontSize: 20 }}>{texto}</Text>
<View style={{ width: "15%" }}>
<Button
onPressIn={() => addTimer(accionMas)}
onPressOut={eraseTimer}
title={titleBotonMas}
/>
</View>
</View>
);
};
const styles = StyleSheet.create({
viewContainer: {
flexDirection: "row",
justifyContent: "center",
paddingTop: 30,
alignItems: "center",
},
});
export default BotonTextoBoton;
uj5u.com熱心網友回復:
該Button組件需要一個onPress方法。這可能無濟于事。比較以下代碼片段以使其更加明確。提供 noonPress等同于傳遞undefined。
<Button onPress={undefined} onPressIn={() => addTimer(accionMas)} onPressOut={eraseTimer} title={"Titlte"} />
這會產生錯誤訊息Please attach a method to this component。
您可以按如下方式解決此問題。
<Button onPress={() => {}} onPressIn={() => addTimer(accionMas)} onPressOut={eraseTimer} title={"Titlte"} />
我們只是提供() => {}什么都不做的功能。該訊息不再出現。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/431309.html
上一篇:React-native:避免使每個經過身份驗證的遠程呼叫異步
下一篇:打字稿導航導航引數錯誤
