簡體   English   中英

從 PanResponder 內部更新 state

[英]Update state from inside a PanResponder

我正在使用 react-native-svg 制作應用程序,但無法從 PanResponder 內部更新組件的 state。

我有一個 < Svg > 元素,其中有一個 < Circle >。 < Circle > 的 position 與名為 originCoords 的變量(一個 state 變量)相關。 我已經使用 PanResponder 來制作它,以便在進行平移手勢時,< Svg >(其中包含 < Circle >)被移動,並且一旦手勢結束,< Svg > 將返回其原始 Z46057FE06FDEDEA636A。

我正在嘗試在平移手勢完成后更改 originCoords,因此,即使 < Svg > 回到原來的 position,< Circle > 仍然保持在其新的 Z4757FE07FD492A8BE60EA6A760EZD68。 但是我很難從 PanResponder 內部的 createPanResponder.js 文件中更改 originCoords 的 state,它只是保持不變,至少在 android 仿真器上是這樣。 任何幫助將非常感激。

這是我的文件:

// MapScreen.js

import React, { useRef, useState } from "react";
import { Animated } from "react-native";
import { Svg, Circle } from "react-native-svg";
import { createPanResponder } from "../services/utils/createPanResponder";

export const MapScreen = () => {
  const [originCoords, setOriginCoords] = useState({x: 0, y: 0});
  const [circleCoords, setCircleCoords] = useState({x: 20, y: 20});

  const pan = useRef(new Animated.ValueXY()).current;
  const panResponder = createPanResponder(pan, originCoords, setOriginCoords);

  return (
    <Animated.View
      style={{transform: [{ translateX: pan.x }, { translateY: pan.y }],}}
      {...panResponder.panHandlers}
    >
      <Svg width='300' height='300' style={{ backgroundColor: "blue" }}>
        <Circle
          cx={`${circleCoords.x - originCoords.x}`}
          cy={`${circleCoords.y - originCoords.y}`}
          r="5"
          stroke="white"
          strokeWidth="1"
        />
      </Svg>
    </Animated.View>
  );
};
import { useRef } from "react";
import { PanResponder, Animated } from "react-native";

export const createPanResponder = (pan, originCoords, setOriginCoords) => {
  return useRef(
    PanResponder.create({
      // PanResponder default configs have been removed to be more succint
      onPanResponderMove: (evt, gestureState) => {
        // sets pan.x and pan.y to equal gesture's deltas
        Animated.event([{ x: pan.x }])({ x: gestureState.dx });
        Animated.event([{ y: pan.y }])({ y: gestureState.dy });
      },

      onPanResponderRelease: (evt, gestureState) => {
        //resets pan.x and pan.y
        Animated.event([{ x: pan.x }])({ x: 0 });
        Animated.event([{ y: pan.y }])({ y: 0 });

        // PROBLEM IS HERE, setOriginCoords DOESN'T DO ANYTHING
        console.log(originCoords); // { x: 0, y: 0 }
        const { dx, dy } = gestureState;
        setOriginCoords({ ...originCoords, dx, dy });
        console.log(originCoords); // { x: 0, y: 0 }
      },
    })
  ).current;
};

雖然我沒有看到將這個function變成 class 組件的失敗原因,但functions沒有state ,只有類有。 這是我今天從這里和文檔中學到的

constructor(props) {
    super(props);
    this.pan = new Animated.ValueXY();
    this.panResponder = PanResponder.create({
      onStartShouldSetPanResponder: (e, state) => false,
      onStartShouldSetPanResponderCapture: (e, state) => false,
      onMoveShouldSetPanResponder: () => true,
      onMoveShouldSetPanResponderCapture: (e, { dx, dy }) => {
        if (Math.abs(dx) > 10 || Math.abs(dy) > 10) {
          this.state.holding && this.setState({ holding: false });
          return true;
        } else {
          !this.state.holding && this.setState({ holding: true });
          return true;
        }
      },
      onPanResponderGrant: (e, gestureState) => {
        this.pan.setOffset(this.pan.__getValue());
        this.pan.setValue({ x: e.nativeEvent.pageX, y: e.nativeEvent.pageY });
      },
      onPanResponderMove: (e, gesture) => {
        this.pan.setValue({ x: gesture.dx, y: gesture.dy });
        /*Animated.event([null, { dx: this.pan.x, dy: this.pan.y }])(
          e,
          gestureState
        );*/
        if (Math.abs(gesture.dx) > 10 || Math.abs(gesture.dy) > 10) {
          clearTimeout(this.t);
          this.state.holding && this.setState({ holding: false });
        } else {
          !this.state.holding && this.setState({ holding: true });
        }
      },
      onPanResponderRelease: (e, { vx, dx }) => {
        this.setState({ holding: false });
        const offScreenX = () => {
          if (this.props.width < e.nativeEvent.pageX) {
            Animated.spring(this.pan.x, {
              toValue: this.props.width - 60,
              bounciness: 10
            }).start();
          } else if (0 > e.nativeEvent.pageX) {
            Animated.spring(this.pan.x, {
              toValue: 0,
              bounciness: 10
            }).start();
          }
        };
        const offScreenY = () => {
          if (this.props.height < e.nativeEvent.pageY) {
            Animated.spring(this.pan.y, {
              toValue: this.props.height - 60,
              bounciness: 10
            }).start();
          } else if (0 > e.nativeEvent.pageY) {
            Animated.spring(this.pan.y, {
              toValue: 0,
              bounciness: 10
            }).start();
          }
        };
        // abs(vx) speed (not velocity) of gesture,
        // abs(dx) distance traveled (not displacement)
        //if (Math.abs(vx) >= 0.5 || Math.abs(dx) >= 30) {
        this.pan.flattenOffset();
        //}
        if (this.props.width / 2 > e.nativeEvent.pageX) {
          if (this.props.height / 2 < e.nativeEvent.pageY) {
            offScreenX();
            Animated.spring(this.pan.y, {
              toValue: this.props.height - 60,
              bounciness: 10
            }).start();
          } else {
            offScreenY();
            Animated.spring(this.pan.x, {
              toValue: 0,
              bounciness: 10
            }).start();
          }
        } else {
          if (this.props.height / 2 > e.nativeEvent.pageY) {
            offScreenX();
            Animated.spring(this.pan.y, {
              toValue: 0,
              bounciness: 10
            }).start();
          } else {
            offScreenY();
            Animated.spring(this.pan.x, {
              toValue: this.props.width - 60,
              bounciness: 10
            }).start();
          }
        }
      }
    });
    this.state = { highAndTight: true, hideOpener: true };
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM