i have a classic functionnal component returning what will be rendered in JSX
function Search(){
const loadFilms = function (){
console.log(this)); // logs undefined
};
return(
<View style= {styleAreas.view}>
<TextInput style= {styleAreas.textinput} placeholder='Type your movie ' />
<Button title='Search' onPress= {()=> { console.log(this);loadFilms();} } /> // logs undefined
<FlatList
data={films}
keyExtractor = {item => item.id.toString()}
renderItem={({item}) => <FilmItem filmDesc = {item} />}
/>
</View>
)
}
so i'm learning JS / React, and what i don't understand why this is undefined but when we run it since Class Search extends React.Component {}. it returns the right instance. especially that i tought that in JS ( i'm maybe over simplifying) a class is a function with pre-configured prototypes etc...
thank you for your explanations :)
Since React is a javascript library, “this” in React follows the same intriguing concept. In javascript, the behaviour of “this” keyword is based on how a function is called. “this” holds the reference to current execution context in javascript.
The shouldComponentUpdate method allows us to exit the complex react update life cycle to avoid calling it again and again on every re-render. It only updates the component if the props passed to it changes.
React components automatically re-render whenever there is a change in their state or props. A simple update of the state, from anywhere in the code, causes all the User Interface (UI) elements to be re-rendered automatically. However, there may be cases where the render() method depends on some other data.
The reason for that is that loadFilms
is a function different from your 'Class'. Therefore, it has a different this context. Since you seem to use strict mode, it's undefined. You could pass it explicitly by using the call method.
function Search(){
const loadFilms = function (){
console.log(this)); // logs undefined
};
return(
<View style= {styleAreas.view}>
<TextInput style= {styleAreas.textinput} placeholder='Type your movie ' />
<Button title='Search' onPress= {()=> { console.log(this); loadFilms.call(this);} } /> // logs undefined
<FlatList
data={films}
keyExtractor = {item => item.id.toString()}
renderItem={({item}) => <FilmItem filmDesc = {item} />}
/>
</View>
)
}
I believe you are mistaken because your function is not extending the Component class.
A react component class would begin with the declaration as so:
class App extends Component {
render () {
return (
<Text>Hello World!</Text>
)
}
}
Class components are functions, but your function is not extending the component class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With