我有一个经典的函数组件返回将在 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>
)
}
所以我正在学习 JS/React,我不明白为什么这是 未定义 但是当我们运行它时,因为 Class Search 扩展了 React.Component {}。它返回正确的实例。
尤其是我认为在 JS 中(我可能过于简化)a 类是一个函数 带有预配置的原型(prototype)等...
谢谢你的解释:)
最佳答案
原因是 loadFilms
是与您的“类”不同的功能。因此,它具有不同的this上下文。由于您似乎使用 strict mode ,它是未定义的。您可以使用 call 显式传递它方法。
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>
)
}
关于javascript - React Js中 'this'的利用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62162780/