0

So here is the code:

export default SomeClass extends React.Component {
    constructor(props) {
        super(props);
    }

    _FunctionA = () => {
        // Do something
    }

    render() {
        const arr = ['1', '2'];

        const buttons = arr.map(function(v, i) {
            return(
                <TouchableOpacity onPress={this._FunctionA}></TouchableOpacity>
            );
        });

        return(
            <View>
                { buttons }
            </View>
        );
    }
}

My problem is why can't I call functionA in the same class inside the map function, I know that there is a problem with this._FunctionA which is not referring to the correct function, but I could not find how and what is the method to call the Function from the map function.

Charas
  • 1,753
  • 4
  • 21
  • 53

1 Answers1

1

In the map function, this takes another value, this doesn't reference class anymore, so in your render function you must reference the class in a var:

render() {
        const arr = ['1', '2'];
        let that = this;
        const buttons = arr.map(function(v, i) {
            return(
                <TouchableOpacity onPress={that._FunctionA}></TouchableOpacity>
            );
        });

        return(
            <View>
                { buttons }
            </View>
        );
    }
Luis Barajas
  • 478
  • 3
  • 12