本教程內(nèi)容和https://zhiwehu.gitbooks.io/react-native/content/ 同步更新群叶。
刪除todo item
本小節(jié)我們來實現(xiàn)如何刪除一條todo item摩幔。首先我們需要使用TouchableOpacity控件來做一個刪除按鈕。
我們在row.js里,在todo item的文字后面增加一個新的刪除按鈕,注意TouchableOpacity
的onPress
事件,綁定的方法是從外層傳遞進來的僻族。
<TouchableOpacity onPress={this.props.onRemove}>
<Text style={styles.remove}>X</Text>
</TouchableOpacity>
接下來在app.js里,我們定義這個方法屡谐,使用Array.filter方法來將需要刪除的item從列表中剔除出來述么。
handleRemoveItem(key) {
const newItems = this.state.items.filter((item) => {
return (item.key !== key);
});
this.setSource(newItems, newItems);
}
接下來,將這個方法傳給Row控件
<Row
key={key}
onRemove = {() => this.handleRemoveItem(key)}
onComplete = {(complete) => this.handleToggleComplete(key, complete)}
{...value}
/>
運行結(jié)果如下:
method.bind(this)
也許你注意到了愕掏,我在app.js的App類的構(gòu)造方法里度秘,將我們定義的方法,通過bind(this)來重新設(shè)置了一下饵撑,為什么我們需要這樣做呢剑梳?
this.setSource = this.setSource.bind(this);
this.handleAddItem = this.handleAddItem.bind(this);
this.handleToggleComplete = this.handleToggleComplete.bind(this);
this.handleRemoveItem = this.handleRemoveItem.bind(this);
比如我們今天的方法handleRemoveItem
是App這個類的方法,在JavaScript中滑潘,類方法是默認(rèn)不綁定的垢乙,所以在handleRemoveItem
這個類方法里,如果我們不將this綁定的話语卤,我們便無法在這個方法里使用this
追逮,否則會報this
會undefined
蓖租。
建議參考這兩篇文章:
- 官網(wǎng)介紹:https://facebook.github.io/react/docs/handling-events.html
- React Binding Patterns: 5 Approaches for Handling
this
代碼:https://github.com/zhiwehu/todo/tree/remove
- React Native實戰(zhàn)開發(fā)1:搭建開發(fā)環(huán)境
- React Native實戰(zhàn)開發(fā)2:布局
- React Native實戰(zhàn)開發(fā)3:模塊劃分
- React Native實戰(zhàn)開發(fā)4:屬性和狀態(tài)
- React Native實戰(zhàn)開發(fā)5:使用TextInput
- React Native實戰(zhàn)開發(fā)6:使用ListView
- React Native實戰(zhàn)開發(fā)7:使用Switch更新todo complete狀態(tài)
- React Native實戰(zhàn)開發(fā)8: 刪除todo item