繁体   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