React Native Passing Functions with Arguments as Props

From what I read, it’s best to try to structure the reaction of applications with as many components as dumb renderers. You have your containers that retrieve data and pass it to components as a props.

This works well until you want to pass functions along a chain that requires arguments other than events.

class MyClass extends Component { _onItemPress (myId) { // do something using myId } render () { return <MyComponent myID={10} onPress={(myId) => this._onItemPress(myId)} /> } } 

If I just pass this as my onPress handler for MyComponent, it will not return myId when called. To get around this, I am doing something like this.

 export default ({myId, onPress) => { const pressProxy = () => { onPress(myId) } return ( <TouchableHighlight onPress={pressProxy}> <Text>Click me to trigger function</Text> </TouchableHighlight> ) } 

Am I doing this completely wrong? I would like to have a simple component that I can reuse for list items, where its only function is to take the title, onpress function and return the list item that will be used in the renderView's ListViews function. However, many onPress features will require variables that will be used in onPress.

Is there a better way?

+6
source share
1 answer

The correct syntax would be something like this:

 render () { let myId = 10; return <MyComponent myID={myId} onPress={() => this._onItemPress(myId)} /> } 

In addition, if you plan to use this inside _onItemPress (for example, to call other methods in MyClass), you need to associate the scope as follows:

 render () { let myId = 10; return <MyComponent myID={myId} onPress={() => this._onItemPress(myId).bind(this)} /> } 

... or you can link it already in the constructor if you want:

 constructor(props) { super(props); this._onItemPress = this._onItemPress.bind(this); } 
+1
source

Source: https://habr.com/ru/post/1011656/


All Articles