javascript 如何在react native中创建多个泛应答器?

zbsbpyhn  于 2022-12-25  发布在  Java
关注(0)|答案(2)|浏览(134)

我知道如何创建一个panResponder,但我不知道如何创建它的多个示例。例如,我有一个独立移动的元素数组,我必须将每个responder分别附加到元素,以获得布局值。任何帮助将被卡住很长一段时间。

pan = new Animated.ValueXY();

    panResponder = PanResponder.create({
        onMoveShouldSetPanResponder: () => true,
        onPanResponderGrant: (evt, gestureState) => {
            this.pan.setOffset(this.pan.__getValue());
            this.pan.setValue({ x: 0, y: 0 });
        },

    onPanResponderMove: Animated.event([
      null,
      { dx: this.pan.x, dy: this.pan.y }
    ]),
    onPanResponderRelease: (e) => {
      console.log(this.pan.getLayout(), 'layout values')
      this.pan.flattenOffset();
    }
  });

 render() {
      
    return (
      <View style={styles.container}>
        <View  style={{backgroundColor:'red', height:300, width:300}}>
            <Animated.View
                pointerEvents="box-none"
                style={[styles.box, {
                    transform: [{ translateX: this.pan.x }, { translateY: this.pan.y }]
                }]}
                {...this.panResponder.panHandlers}>
        </Animated.View>
      </View>
      </View>
    );
  }
x9ybnkn6

x9ybnkn61#

1.您可以根据数组创建多个引用父组件本身的示例,并将PanResponder附加到它

class Parent extends Component {
  constructor(props) {
    super(props);
    this.panRefs = this.props.elements.map(e => React.createRef());

    this.panRefs.forEach(panRef => {
      panRef.current = PanResponder.create({})
    });
  }

  render() {}
}

1.您可以创建一个子组件并将PanResponder附加到它的ref。

class Parent extends Component {
  render() {
    const arr = Array.from({ length: 8 });

    return (
      <View>
        {arr.map((elem, idx) => {
          return <Child elem={elem} key={idx} />
        })}
      </View>
    )
  }
}

class Child extends Component {
  constructor(props) {
    super(props);

    this.panRef = React.createRef();

    this.panRef.current = PanResponder.create({})
  }

  render() {}
}
c3frrgcw

c3frrgcw2#

我在onPanResponderMove()中添加了一些变通方法来支持多点触控,请参阅https://github.com/flyskywhy/react-native-gcanvas/blob/master/components/GCanvasComponent.js#L42,下面是react-native-babylonjs多点触控演示的结果:

相关问题