On Press侦听器会阻止父组件PanResponder

时间:2019-07-13 01:12:43

标签: javascript reactjs react-native

我有一个Animated.View组件,它具有一个PanResponder以使其可拖动。 这个Animated.View组件有一个Text子元素,该子元素的onLongPress事件侦听器设置为稍后可以执行某些操作...

问题在于,它像onLongPress事件侦听器一样也正在“捕获”正常的按下动作(PanResponder也是必需的。

是否可以将Text的常规onPress传递给PanResponder,取消它或手动触发onStartShouldSetPanResponder,以免打扰PanResponder,除非这是实际的长按? / p>

建设者

constructor(props) {
    super(props);
    this.state = {
      showDraggable: true,
      dropAreaValues: null,
      pan: new Animated.ValueXY(),
      opacity: new Animated.Value(1),
      text: "Hello World"
    };
    this._val = { x: 0, y: 0 };
    this.state.pan.addListener(value => (this._val = value));

    this.panResponder = PanResponder.create({
      onStartShouldSetPanResponder: (e, gesture) => true,
      onPanResponderGrant: (e, gesture) => {
        this.state.pan.setOffset({
          x: this._val.x,
          y: this._val.y
        });
        this.state.pan.setValue({ x: 0, y: 0 });
      },
      onPanResponderMove: Animated.event([
        null,
        { dx: this.state.pan.x, dy: this.state.pan.y }
      ])
    });
  }

渲染

render() {
    const panStyle = {
      transform: this.state.pan.getTranslateTransform()
    };
    return (
      <View
        style={{
          position: "absolute",
          top: this.props.top
        }}
      >
     <Animated.View {...this.panResponder.panHandlers} style={[panStyle]}>
     <View style={{ zIndex: 250,
        padding: 10,
          borderWidth: 2,
          borderColor: "yellow"}}>

          <Text style={{fontSize: 24}} onLongPress={() => {
              console.log("Long press recognized")
          }}>{this.state.text}</Text>
          </View>
        </Animated.View> 
      </View>
    );
  }

(边界是为了使Views边界可见,而在问题上并不重要)

1 个答案:

答案 0 :(得分:0)

解决方案是使用Animated.Text 它可以与PanResponder一起使用。