美文网首页
ListView简单实例

ListView简单实例

作者: ZKey | 来源:发表于2016-06-22 11:42 被阅读171次

    当我们要做一些列表 我想ListView是再适合不过的组件了 在RN里面算是一个核心组件,用于高效地显示一个可以垂直滚动的变化的数据列表。
    废话不多说 开始来做吧

    第一步

    如果我们要做一个列表 那么我们先要做出 里面里面每个item吧
    Item代码如下:List.js

    import React from 'react';
    import {
      StyleSheet,
      Text,
      View,
      Image,
      TouchableHighlight
    } from 'react-native';
    
    export default class List extends React.Component {
      constructor(props) {
        super(props);
      }
    
      render() {
        return (
          <TouchableHighlight 
            style={styles.tbox}
            underlayColor='#fff'
            onPress={()=>{}}>
            <View style={styles.box}>
                <Image source={{uri:this.props.src}} style={styles.img} />
                <View style={styles.txt}>
                    <Text style={styles.title}>{this.props.title}</Text>
                    <Text style={styles.time}>{this.props.time} | {this.props.id}</Text>
                </View>
            </View>
          </TouchableHighlight>
        );
      }
    }
    
    const styles = StyleSheet.create({
      tbox:{
        backgroundColor:'#f5f5f5',
      },
      box:{
        flexDirection:'row',
        padding:5,
        borderBottomWidth:1,
        borderColor:'#eee',
      },
      img:{
        flex:3.8,
        resizeMode:Image.resizeMode.contain,
        height:100
      },
      txt:{
        flex:6.2,
        paddingLeft:8,
        paddingRight:3,
      },
      title:{
        lineHeight:22,
      },
      time:{
        marginTop:30,
        color:'#999'
      }
    });
    

    很简单 单个的item就做好了 它的样子应该是这样的

    List

    第二步

    我们要开始做ListView了
    新建一个文件叫Main.js
    首先在我们在构造函数里 定义我们的state

    constructor(props) {
        super(props);
    
        this.ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.state = {
          dataSource:this.ds,
        }
      }
    

    然后我们要加载数据 一般加载数据我会在组件渲染完成后执行也就是componentDidMount里面 这里载入数据的我用的是fetch 代码如下:

    componentDidMount() {
        fetch('http://ued.yihaodian.com:3001/api/70')
          .then((response) => response.json())
          .then((data) => {
            this.setState({
              dataSource:this.ds.cloneWithRows(data.listData)
            })
          })
          .done();
    }
    

    数据应该长这样:


    api data

    后面就是把List模块渲染到ListView里面去了

    rendList(data){
        return (
          <List
            src={data.src}
            title={data.title}
            time={data.time}
            id={data.id} />
        )
    }
    
    ...
    
    render() {
        return (
            <ListView
              dataSource={this.state.dataSource}
              renderRow={this.rendList}  />
        );
    }
    

    最终效果图:

    Paste_Image.png

    那么一个简单的ListView的实例就完成了
    后面我会讲一下ListView如何实现下拉时动态渲染数据

    相关文章

      网友评论

          本文标题:ListView简单实例

          本文链接:https://www.haomeiwen.com/subject/znzgdttx.html