react-native的ListView控件的使用

来源:互联网 发布:springmvc json 编辑:程序博客网 时间:2024/05/17 23:45

react-native的ListView控件的使用

1.数据准备

    // 在构造方法中准备    constructor(props) {        super(props);        this.state = {            // 创建一个DataSource            dataSource: new ListView.DataSource({                rowHasChanged: ((row1, row2) => row1 !== row2)            }),            // 是否加载完毕            load: false        }    }

2.创建ListView

    render() {        return (            <View>                <ListView                    dataSource={this.state.dataSource}                    {/*这里是每个item的布局,这里在方法中实现*/}                    renderRow={this.getItemView}                />            </View>        );    }        getItemView(item) {        return (            <View>                <Text style={styles.itemHeader}>{item.desc}</Text>                <View style={styles.item}>                    <Text style={styles.itemMeta}>{item.who}</Text>                    <Text style={styles.itemMeta}>{item.createdAt}</Text>                </View>            </View>        );    }

3.在componentDidMount生命周期中执行数据请求

    // 发起数据请求    componentDidMount() {        this.getMoviesFromApiAsync();    }    // 使用自带的网络请求请求数据    getMoviesFromApiAsync() {        fetch('http://gank.io/api/data/Android/10/1')            .then((response) => response.json())            .then((responseJson) => {                this.setState({                    //改变加载ListView                    load: true,                    //设置数据源刷新界面                    dataSource: this.state.dataSource.cloneWithRows(responseJson.results),                })            })            .catch((error) => {                console.error(error);            });    }
原创粉丝点击