ScrollView React Собственный горизонтальный не работает - PullRequest
2 голосов
/ 23 июня 2019

Я занимаюсь разработкой приложения с RN 0.59.8. Я пытаюсь создать прокручиваемый вид по горизонтали с помощью ScrollView. Вот основа моего кода (извините, я не мог поделиться более подробной информацией):

import React, { Component, Fragment } from 'react';
import {
  ScrollView,
} from 'react-native';
import {
  Container,
  Content,
} from 'native-base';
import { Grid, Row } from 'react-native-easy-grid';

import ChildComponent from './ChildComponent';

class MyComponent extends Component {
  render() {
    const {
      data,
    } = this.props;

    return (
      <Container>
        <Content>
          <Grid>
            <Row>
              <ScrollView
                horizontal
                contentContainerStyle={{
                  flex: 1, flexGrow: 1, flexDirection: 'row',
                }}
              >
                {
                  data.map((item, index) => {
                    const order = index;

                    return (
                      <Fragment key={order}>
                        {
                          <ChildComponent />
                        }
                      </Fragment>
                    );
                  })
                }
              </ScrollView>
            </Row>
          </Grid>
        </Content>
      </Container>
    );
  }
}

export default MyComponent;

Текущее поведение:

  1. если contentContainerStyle={{ flex: 1, flexGrow: 1, flexDirection: 'row' }}, вторые данные не отображаются
  2. если contentContainerStyle={{ flex: 1, flexGrow: 1, flexDirection: 'column' }}, вторые данные отображаются вертикально
  3. если contentContainerStyle={{ flexDirection: 'row' }}, вторые данные не отображаются, а содержимое шире ширины экрана

Мое возражение :

  1. Я хочу сделать горизонтальную прокрутку
  2. Каждые данные будут соответствовать ширине экрана

Любая помощь будет очень полезна. Спасибо !!!

1 Ответ

0 голосов
/ 23 июня 2019

Прямо из React Native docs, для того, чтобы дочерние элементы представления прокрутки располагались по горизонтали в ряду, а не по вертикали в столбце, единственная опора, которую вам нужно использовать, это horizontal.

<ScrollView horizontal>
  <Child/>
</ScrollView>

Я создал закуску, чтобы показать вам, @ abranhe / stackoverflow-56721203 :

image

, чтобы она соответствовала ширине экрана, поиграйте сваш компонент и:

import { Dimensions } from 'react-native';

Dimensions.get('width').width

Исходный код демо:

import React, { Component } from 'react';
import { Text, View, StyleSheet, Image, ScrollView } from 'react-native';
import data from './data';

export default class App extends Component {
  renderCity(city) {
    return (
      <View style={styles.cardContainer}>
        <View style={styles.card}>
          <Image source={{ uri: city.img }} style={styles.image} />
          <Text style={styles.title}>{city.title}</Text>
        </View>
      </View>
    );
  }

  render() {
    return (
      <View style={styles.container}>
        <ScrollView horizontal>
          {data.map(city => {
            return this.renderCity(city);
          })}
        </ScrollView>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#ecf0f1',
    marginTop: 30,
  },
  title: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
  image: {
    width: 200,
    height: 200,
    borderRadius: 10,
    marginTop: 10,
  },
  cardContainer: {
    justifyContent: 'center',
  },
  card: {
    backgroundColor: 'white',
    justifyContent: 'center',
    alignItems: 'center',
    margin: 20,
    borderRadius: 10,
    width: 220,
  },
});

Имейте в виду

Некоторые пользовательский интерфейскомпоненты из native-base имеют абсолютные значения, вы можете изменить переменные темы, чтобы они соответствовали вашим потребностям.

Если вы не хотите показывать индикатор прокрутки, вы можете установить false ScrollView's showsHorizontalScrollIndicator prop.

...