简体   繁体   中英

Multiple PanResponder (draggable) elements in React Native

Just looking for some pointers to make a second draggable element in React Native using the PanResponder.

So I've got this code in the componentWillMount function

  componentWillMount = () => { this._panResponder = PanResponder.create({ onStartShouldSetPanResponder: this._alwaysTrue, onMoveShouldSetPanResponder: this._alwaysTrue, onPanResponderGrant: this._handlePanResponderGrant, onPanResponderMove: this._handlePanResponderMove, onPanResponderRelease: this._handlePanResponderEnd, onPanResponderTerminate: this._handlePanResponderEnd }); 
Now obviously all the functions such as _handlePanResponderMove are defined as well.

I then bind that to an SVG element with

 <Circle cx={this.state.x} cy={this.state.y} r="45" fill="white" {...this._panResponder.panHandlers} /> 

Now that works fine if I just have a single SVG circle I want to make draggable. How would I go about doing this for a second circle - I'm sure there must be a better way than creating a new panResponder with all functions? Putting the same {...this._panResponder.panHandlers} in a second SVG circle obviously won't work; both circles will then move at the same time, into the same positions.

Any pointers would be greatly appreciated. Thanks!

So I found a temporary fix, by just creating two PanResponders. It's not ideal (not DRY), as a large amount of code is repeated. I don't have enough experience in JS to figure out how to pass correct params to these functions, so this will have to do for now.

  this._panResponder = PanResponder.create({ onMoveShouldSetPanResponder: this._alwaysTrue, onPanResponderMove: (evt, gestureState) => { this.setState({ x: this._previousLeft + gestureState.dx, y: this._previousTop + gestureState.dy }); }, onPanResponderEnd: (evt, gestureState) => { this._previousLeft += gestureState.dx; this._previousTop += gestureState.dy; }, }); this._secondPanResponder = PanResponder.create({ onMoveShouldSetPanResponder: this._alwaysTrue, onPanResponderMove: (evt, gestureState) => { this.setState({ xS: this._previousSLeft + gestureState.dx, yS: this._previousSTop + gestureState.dy }); }, onPanResponderEnd: (evt, gestureState) => { this._previousSLeft += gestureState.dx; this._previousSTop += gestureState.dy; }, }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM