React Native绑定函数失效求助:基于react-native-interactable库
Hey there, let's get your interactable view's functions working properly! The most common culprit here is incorrect function binding in class components, paired with missing required props for the interactable view. Here's how to fix it step by step:
1. Fix Function Binding to the Component Instance
In React class components, regular class methods don't automatically bind to the component's this context. You have two easy ways to fix this:
Option A: Bind in the Constructor
import { Component } from 'react'; import { View } from 'react-native'; import Interactable from 'react-native-interactable'; class MainScreen extends Component { constructor(props) { super(props); // Bind your methods to the component instance here this.onDrag = this.onDrag.bind(this); this.onSnap = this.onSnap.bind(this); } onDrag() { console.log("dragging...") } onSnap() { console.log("snapped!") } render() { return( <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}> <Interactable.View style={{backgroundColor: '#000000', width: 100, height: 100}} onDrag={this.onDrag} onSnap={this.onSnap} snapPoints={[{x: 0, y: 0}, {x: 200, y: 0}]} /> </View> ) } }
Option B: Use Arrow Function Class Fields
This avoids manual binding entirely by defining methods as arrow functions:
import { Component } from 'react'; import { View } from 'react-native'; import Interactable from 'react-native-interactable'; class MainScreen extends Component { // Define methods as arrow functions to auto-bind to `this` onDrag = () => { console.log("dragging...") } onSnap = () => { console.log("snapped!") } render() { return( <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}> <Interactable.View style={{backgroundColor: '#000000', width: 100, height: 100}} onDrag={this.onDrag} onSnap={this.onSnap} snapPoints={[{x: 0, y: 0}, {x: 200, y: 0}]} /> </View> ) } }
2. Ensure Required Interactable Props Are Set
- The
onSnapcallback only triggers when the view snaps to a predefined point, so you must include thesnapPointsprop (like in the examples above) to make it work. - For drag-related callbacks, confirm you're using the correct prop name: the library uses
onDrag,onDragStart, andonDragEnddepending on when you want the trigger to fire. - Make sure the parent
Viewhas enough space (setflex: 1) so the interactable view can be dragged freely.
3. Double-Check Library Installation
If you're still having issues, verify you have the latest version of the library installed, and that it's properly linked (automatic linking works for React Native 0.60+; for older versions, follow the library's manual linking steps).
内容的提问来源于stack exchange,提问作者Ketan Malhotra

