1
As you know I’m joining this world of Javascript/React Native... In my studies I have noticed in some examples how certain functions are called.
- Example 1: In this example the onCancel function is called when the user presses Touchableopacity:
<TouchableOpacity onPress={this.props.onCancel}>
<Text style={styles.button}>Cancelar</Text>
</TouchableOpacity>
- Example 2: In this example the setState function, which changes the state of the component, is called when the user presses Touchableopacity, but note that here it is present in an Arrow function, unlike example 1:
<TouchableOpacity style={styles.addButton} onPress={() => this.setState({ showAddTask: true })}>
<Icon name='plus' size={20} color={commonStyles.colors.secondary} />
</TouchableOpacity>
- Example 3:In this example the toggleFilter function is called when the user presses Touchableopacity and just like in Example 1 the same does not apply to an Arrow Function:
<TouchableOpacity onPress={this.toggleFilter}>
<Icon />
</TouchableOpacity>
- Example 4: In this example the setState function, which changes the state of the component, is called when the user changes the content of Textinput, but note that here it is present in an Arrow function, unlike example 1:
<TextInput onChangeText={desc => this.setState({ desc })} value={this.state.desc} />
- Example 5: In this example I have the getDateTimePicker function which returns a Datetimepicker component. Since this is a class component right after I return a JSX in the render, note that I call getDateTimePicker directly, without Arrow Function, and it will return the Datetimepicker component:
getDateTimePicker = () => {
return (
<DateTimePicker
value={this.state.date}
onChange={(_, date) => this.setState({ date })}
mode='date'
/>
)
}
render() {
return (
<Text style={styles.header}>Nova Tarefa</Text>
{this.getDateTimePicker()}
)}
Because sometimes we call "direct" functions without parentheses, other times we call direct with parentheses (example 5) and other times we put inside Arrows functions as in the above examples?
My friend, can you explain to me what it would be like to "pass a function as reference"?
– Bruno Nobre
It would assign its function to that memory address. Thus, ensuring that its function is called when a certain item is invoked. For example: in onPress events, when you pass the function reference, you are passing a memory address, which will invoke its function when the event is triggered.
– Wesley Ferreira
My friend Wesley, thank you for the detail in your explanations, to "close with a golden key" just helps me in this excerpt of your explanation, please. You say, "In this first situation, the use of callback causes the function reference to be passed directly to the event, sometimes you cannot pass a certain item that is in the scope of the function to your callback." I don’t understand what you meant by that part
– Bruno Nobre