反应原生如何检测左侧是否被触摸或右侧

时间:2021-05-30 16:45:49

标签: react-native expo

我制作了一个 Instagram 故事克隆,但我被一件事困住了。如何检测是触摸左侧还是右侧?因为用户触摸左边可以看到上一个故事,或者触摸右边可以看到下一个故事。

1 个答案:

答案 0 :(得分:1)

import React from "react";
import {
  Dimensions,
  StyleSheet,
  View,
  Text,
  TouchableOpacity
} from "react-native";

const SCREEN_WIDTH = Dimensions.get("screen").width;

const App = () => {
  const handleLeft = () => {
    console.log("left side tapped");
  };

  const handleRight = () => {
    console.log("right side tapped");
  };

  return (
    <View style={styles.container}>
      <TouchableOpacity
        onPress={handleLeft}
        style={[styles.touchable, styles.left]}
      >
        <Text>Left side</Text>
      </TouchableOpacity>
      <TouchableOpacity
        onPress={handleRight}
        style={[styles.touchable, styles.right]}
      >
        <Text>Right side</Text>
      </TouchableOpacity>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flexDirection: "row"
  },
  touchable: {
    flex: 1,
    width: SCREEN_WIDTH / 2
  },
  left: {
    backgroundColor: "navy"
  },
  right: {
    backgroundColor: "tomato"
  }
});

export default App;