[英]React Native - Passing Strings or Variables via onPress
這可能不僅僅適用於React Native,但我確實想了解這里發生了什么。
采取以下5行代碼。 第3行將導致該應用無法在Expo中呈現。
<Button onPress={this.filterOfficeTypePitt} title="Pitt" />
<Button onPress={this.filterOfficeTypeAtl} title="Atl" />
<Button onPress={this.filterOfficeType("pitt")} title="DOES NOT WORK" />
<Button onPress={(e) => this.filterOfficeType("pitt")} title="Pitt" />
<Button onPress={(e) => this.filterOfficeType("atl")} title="Atl" />
我有點理解每一行的情況。
第1和2行:直接調用組件中的方法。
第3行:嘗試做同樣的事情並傳遞一個值。 這會導致應用程序崩潰。 原因是超過了最大深度。
第4和5行:我認為這是一個傳遞anon函數的函數,突然間我可以添加一個字符串值。
一旦使用4和5,我就可以使用一種方法來過濾列表。 當我使用1和2時,我必須為每種方法都有一個獨特的方法。
我只想了解它會發生什么,以及為什么恰好#3無法正常工作。 我確定我至少需要對箭頭功能有更好的了解。
包括輔助函數的代碼。 它基本上從索引數組中獲取數據,並將其推入FlatList組件。
filterOfficeType(officetype){
let newarray = [];
this.state.fulldataSource.forEach((element, index) => {
if(element.office === officetype) {
newarray.push(element);
}
});
this.setState({
dataSource:newarray,
office:officetype
});
}
filterOfficeTypePitt = () => {
this.filterOfficeType("pitt");
}
filterOfficeTypeAtl = () => {
this.filterOfficeType("atl");
}
第3行正在執行該函數,並嘗試將其結果分配給onPress
prop。 它永遠不會到達那里(為什么?:在下面解釋)
const Button = {
onPress: this.filterOfficeType("pitt")
}
注意:函數在創建Button對象時被調用。
而其他行將功能分配給onPress屬性
const Button = {
onPress: this. filterOfficeTypePitt
}
要么
const Button = {
onPress: (e) => {
this.filterOfficeType("pitt")
}
}
注意:該函數不被稱為Button
對象的創建,而是當有人按下該按鈕時
第3行為何導致應用程序崩潰的原因是,它通過調用setState
觸發狀態更改。 調用setState
,react將再次調用render()
。 但是此render()
將再次執行該函數,這將調用setState
並作出反應將再次調用render()
,因此超出最大深度並崩潰
箭頭功能和普通功能之間的主要區別在this
范圍。 在箭頭函數中, this
引用其父對象,而在正常函數中, this
引用自身。 您可以閱讀有關箭頭功能的更多信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.