【问题标题】:Update state from inside a PanResponder从 PanResponder 内部更新状态
【发布时间】:2020-07-25 05:17:31
【问题描述】:

我正在使用 react-native-svg 制作应用程序,但无法从 PanResponder 内部更新组件的状态。

我有一个 元素,其中有一个 。 的位置是相对于一个名为 originCoords 的变量(一个状态变量)。我已经使用 PanResponder 来制作它,以便在进行平移手势时,移动 (其中包含 ),并且一旦手势结束, 就会回到其原始位置。

我正在尝试在平移手势完成后更改 originCoords,因此,即使 回到其原始位置, 仍保持在其新位置。但是我很难从 PanResponder 内部的 createPanResponder.js 文件中更改 originCoords 的状态,它只是保持不变,至少在 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;
};

【问题讨论】:

    标签: javascript reactjs react-native svg react-native-android


    【解决方案1】:

    虽然我没有看到将 function 设为类组件的失败原因,但 functions 没有 state,只有类有。这是我今天学到的 from here 和文档

    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 };
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-05
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      • 2021-10-06
      • 2018-09-01
      • 1970-01-01
      • 2023-02-13
      相关资源
      最近更新 更多