0

I am looping over an array and everytime the text at the index is clicked , i get it printed but i am using bind everytime .How can we do it without bind and just es6.

for(let index=1;index<=10;index++){
            arr.push(
                <TouchableOpacity
                    activeOpacity={0.7}
                    key={index}
                    onPress={this.Updatefunction.bind(this, index)}
                >
                    <Text>
                        {index}
                    </Text>

                </TouchableOpacity>
            );
        }

i want to access the index but don't want to do binding.

2 Answers2

0

You can go with the additional syntax

like use arrow function,

for(let index = 1; index <= 10; index++){
            arr.push(
                <TouchableOpacity
                    activeOpacity={0.7}
                    key={index}
                    onPress={() => this.Updatefunction(this, index)}
                >
                    <Text>
                        {index}
                    </Text>

                </TouchableOpacity>
            );
        }

Here each time render is called an anonymous function is created and that function when called, calls this.onClick.

However consider the case below your function look like

Updatefunction = (this, index) => {
    // your code here
}

In above case, the arrow function does not recreate function everytime, but binds the context to the React component as An arrow function does not have its own this; the this value of the enclosing execution context is used. once when the class is instantiated. This is similar to how binding works is constructor. This is a part of proposed class fields for arrow functions and it isn't a ES6 feature,

Hardik Virani
  • 1,687
  • 7
  • 23
  • 36
  • I've seen you've added an improvement to [this](https://stackoverflow.com/questions/43176862/get-current-location-latitude-and-longitude-in-reactnative-using-react-native-m/43188042#43188042). I hope you can add more than just the code to explain the how and why of that part of code to approve it. – Sebastián Palma Feb 01 '19 at 12:36
0

You can easily use the ES6 way to define your functions which are arrow functions and then call it like this

for(let index=1;index<=10;index++){
            arr.push(
                <TouchableOpacity
                    activeOpacity={0.7}
                    key={index}
                    onPress={() => this.Updatefunction(this, index)}
                >
                    <Text>
                        {index}
                    </Text>

                </TouchableOpacity>
            );
        }

And define your function like

Updatefunction = (this, index) => {
// your code here
}
Ritviz Sharma
  • 306
  • 1
  • 9