【ReactNative】入门:从todo App开始(3)

1.ListView展示todo items

先阅读文档, 了解 ListView 是用来动态展示竖向滑动列表内容的重要component。会用到的的方法有 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([])
这两行的作用是让列表中内容变化的时候渲染更有效率。这两行只要要到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 />中有两个方法,renderRow中单独把key拿出来,是因为listView的每一个list项都要有一个独一无二key。

2. 写helper function:setSource()

每次this.state.items中的值发生变化(比如增添新的item或者删除等)时需要re-render dataSource。

setSource(items, itemsDatasource, otherState = {}) {
    this.setState({
      items,
      dataSource: this.state.dataSource.cloneWithRows(itemsDatasource),
      ...otherState
    })
  }

替换handleToggleAllComplete,handleAddItem这两个方法中的原来的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: '' });
  }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容