1.ListView展示todo items
先閱讀文檔渣刷, 了解 ListView 是用來(lái)動(dòng)態(tài)展示豎向滑動(dòng)列表內(nèi)容的重要component。會(huì)用到的的方法有 renderRow
, renderSeparator
廉嚼。
首先import需要的ListView和Keyboard
import { ... ListView, Keyboard } from 'react-native';
要使用ListView展示列要添加兩行固定代碼:
constructor(props) {
super(props);
/* 固定 */
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
allComplete: false,
value: '',
items: [],
/* 固定 */
dataSource: ds.cloneWithRows([])
}
...
}
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
dataSource: ds.cloneWithRows([])
這兩行的作用是讓列表中內(nèi)容變化的時(shí)候渲染更有效率疲吸。這兩行只要要到listview就要這么寫。具體了解可以看文檔前鹅。
然后在render方法中找到content部分的view摘悴,并在其中添加ListView
<View style={styles.content}>
<ListView
style={styles.list}
enableEmptySections
dataSource={this.state.dataSource}
onScroll={() => Keyboard.dismiss()}
renderRow={({ Key, ...value}) => {
return (
<Row
key={key}
{...value}
/>
)
}}
renderSeparator={(sectionId, rowId) => {
return <View key={rowId} style={styles.separator} />
}}
/>
</View>
...
...
const styles = StyleSheet.create({
...省略之前的
list: {
backgroundColor: '#FFF'
},
separator: {
borderWidth: 1,
borderColor: "#F5F5F5"
}
})
<ListView />中有兩個(gè)方法,renderRow中單獨(dú)把key拿出來(lái)舰绘,是因?yàn)閘istView的每一個(gè)list項(xiàng)都要有一個(gè)獨(dú)一無(wú)二key蹂喻。
2. 寫helper function:setSource()
每次this.state.items中的值發(fā)生變化(比如增添新的item或者刪除等)時(shí)需要re-render dataSource。
setSource(items, itemsDatasource, otherState = {}) {
this.setState({
items,
dataSource: this.state.dataSource.cloneWithRows(itemsDatasource),
...otherState
})
}
替換handleToggleAllComplete
,handleAddItem
這兩個(gè)方法中的原來(lái)的setState
為新的setSource
方法捂寿。
handleToggleAllComplete() {
const complete = !this.state.allComplete;
const newItems = this.state.items.map((item) => ({
...item,
complete
}))
this.setSource(newItems, newItems, { allComplete: complete });
}
handleAddItem() {
if(!this.state.value) return;
const newItems = [
...this.state.items,
{
key: Date.now(),
text: this.state.value,
complete: false
}
]
this.setSource(newItems, newItems, { value: '' });
}