React Native onPress gets called automatically

I'm having problems with the onPress function. OnPress should only work when it was actually triggered by a touch event (I suppose), that is, when I click a button on the screen. But it seems that onPress launches itself when the render function is called. When I try to click manually, this will not work.

import React, { Component } from 'react'; import { PropTypes, Text, View ,Alert } from 'react-native'; import { Button } from 'react-native-material-design'; export default class Home extends Component { render() { return ( <View style={{flex:1}}> <Button value="Contacts" raised={true} onPress={this.handleRoute('x')} /> <Button value="Contacts" raised={true} onPress={this.handleRoute('y')} /> <Button value="Contacts" raised={true} onPress={this.handleRoute('z')} /> </View> ); } handleRoute(route){ alert(route) // >> x , y, z } } module.exports = Home; 

What am I missing? Is there something wrong with the way I assigned, or is this some kind of mistake? Any suggestion is much appreciated.

Video

+36
source share
3 answers

try to change

onPress = {this.handleRoute ('x')} // in this case, the handleRoute function is called as soon as the rendering is done

to

onPress = {() => this.handleRoute.bind ('x')} // in this case handleRoute is not called as soon as rendering is done

+96
source

You can change this:

 onPress={this.handleRoute.bind(this, 'x')} 

or that:

 onPress={() => this.handleRoute('x')} 

The reason is that onPress accepts the function as an argument. In your code, you call the function and immediately return the result (when render is called), rather than referring to the function that React calls later in the press event.

The reason you need to bind (this) is because the function loses the bound instance when you just do (this.handleRoute), and you have to tell it which one to use. The bind function takes other arguments for the subsequent function call. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind for more information on binding.

There is another way to bind in the constructor. You can read about ways to solve this problem in React here: https://facebook.imtqy.com/react/docs/handling-events.html

+68
source

Actually, I declared my function above render, and then from this function I called the function that was declared inside the render () function, and it showed that the function inside render does not exist ... Can someone help me

0
source

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


All Articles