Home > Back-end >  (TypeScript, react native) setTimeout in combination with onPressIn and onPressOut
(TypeScript, react native) setTimeout in combination with onPressIn and onPressOut

Time:02-23

I'm new to React Native and I'm building my first app. I have a button component which when pressed does something and when held pressed does the same but repeatedly. To achieve that I built a simple logic but I can't get it to work properly since when I hold the button pressed it does what it should but the console says:

"Please attach a method to this component"

That message displays when I let the button go so I think the problem is in the onPressOut.

this is the code, sorry about the spanish lenguage in the code :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;

CodePudding user response:

The Button component requires a onPress method. This could be doing nothing. Compare the following code snippet to make this more explicit. Providing no onPress is equivalent with passing undefined.

<Button onPress={undefined} onPressIn={() => addTimer(accionMas)} onPressOut={eraseTimer} title={"Titlte"} />

This yields the error message Please attach a method to this component.

You can fix this as follows.

<Button onPress={() => {}} onPressIn={() => addTimer(accionMas)} onPressOut={eraseTimer} title={"Titlte"} />

We just provide the function () => {} which does nothing. The message does no longer occur.

  • Related