Отображение списка на начальной странице с помощью react-native для Android

#android #react-native

#Android #react-native

Вопрос:

введите описание изображения здесь

Всем привет,

Я новичок в разработке Android с использованием react-native, и я получил эту ошибку, из-за которой я понятия не имею, откуда это взялось, потому что я вообще не использую ScrollView! Я пытаюсь отобразить список на начальном экране, и его данные поступают из вызова api.

Мой код

     import React, { Component } from 'react';
    import {
      Image,
      ListView,
      TouchableHighlight,
      Text,
      View,
      StyleSheet
    } from 'react-native';
    import Api from '../../Utils/api';
    import CategoryRow from './CategoryRow';

    const styles = StyleSheet.create({
      container: {
        flex: 1,
        padding: 12,
        flexDirection: 'row',
        alignItems: 'center',
      },
      text: {
        marginLeft: 12,
        fontSize: 16,
      },
      photo: {
        height: 40,
        width: 40,
        borderRadius: 20,
      },
      separator: {
        flex: 1,
        height: StyleSheet.hairlineWidth,
        backgroundColor: '#8E8E8E',
      }
    });

    class Main extends React.Component {

      constructor(props){

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

        this.state = {
          dataSource: ds.cloneWithRows(['row 1', 'row 2'])
        }
      }

      componentDidMount(){

        Api.getCategories()
          .then((res) => {
            this.setState({
              dataSource: ds.cloneWithRows(res)
            })
          })
          .catch();
      }

      render() {
        return(

          <ListView
            style={styles.container}
            dataSource = {this.state.dataSource}
            renderRow={(data) => <CategoryRow {...data} />}
          />

        )
      }
    }

    module.exports = Main;
  

И код для categoryRow:

     import React from 'react';
    import { View, Text, StyleSheet } from 'react-native';

    const styles = StyleSheet.create({
      container: {
        flex: 1,
        padding: 12,
        flexDirection: 'row',
        alignItems: 'center',
      },
      text: {
        marginLeft: 12,
        fontSize: 16,
      },
      photo: {
        height: 40,
        width: 40,
        borderRadius: 20,
      },
    });

    const CategoryRow = (props) => (
      <View style={styles.container}>
        <Text style={styles.text}>
          ${props.name}
        </Text>
      </View>
    );

    export default CategoryRow;
  

Пример данных :

 [
  {
    "categoryId": 1,
    "code": "15",
    "name": "Photography",
    "description": "Are you a photo junkie? Then join the “snap pack” and travel to some of the most photogenic places on earth. Our photography trips put you on an itinerary specially geared towards getting the perfect pic, with a group of like-minded travellers. Learn new tricks, share your knowledge, and never worry about taking the time to get the shot. Bonus: someone always has an extra lens cap.",
    "categoryTypeId": 1,
    "categoryType": {
      "categoryTypeId": 1,
      "name": "Activity"
    }
  }
]
  

Может кто-нибудь, пожалуйста, помочь мне выяснить, в чем проблема и как устранить эту ошибку?

Ответ №1:

Я думаю, что ListView использует реквизит ScrollView. Смотрите здесь http://facebook.github.io/react-native/releases/0.35/docs/listview.html#scrollview

Из ошибки кажется, что вы должны указать alignItems: 'center' в contentContainerStyle реквизите ListView . Удалите его из styles.container

 <ListView contentContainerStyle={{alignItems: 'center'}}>
    ....
</ListView>
  

Комментарии:

1. То есть вы имеете в виду, что я должен обернуть ListView с помощью ScrollView?

Ответ №2:

   render() {
    return(
       <View style={{
          alignItems: 'center'
        }}>
           <ListView
              style={styles.container}
              dataSource = {this.state.dataSource}
              renderRow={(data) => <CategoryRow {...data} />}
           />)
     </View>
  }