Как использовать justifyContent и alignItems в собственном плоском списке реагирования с помощью contentContainerStyle и т. Д. - PullRequest
0 голосов
/ 29 апреля 2020

Я использую реагировать родной. Теперь, когда я пытаюсь центрировать плоский список по центру экрана, либо указав плоский список с помощью justifyContent и alignItems, это вызывает у меня странное действие. Кроме того, contentContainerStyle с justifyContent и alignItems в качестве центра также дает странное действие. Весь день искал решения. Я предоставлю код и изображение ниже. Спасибо.

Я пытаюсь выровнять этот плоский список по центру, как это сделали бы justfyContent и alignItems. Вы можете видеть, что контент наклоняется к левой части экрана.

enter image description here

import React, { useState } from "react";
import { View, Text , Button, FlatList, ActivityIndicator, TouchableOpacity } from "react-native";
import { GlobalStyles } from "../styles/GlobalStyles";
import PokeDetails from "./PokeDetails";
import SearchBarComponent from "../components/SearchBar";
import PokeBanner from "../components/PokeBanner";

class Home extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            isLoading: true,
            dataSource: [],
        }
    }

    componentDidMount() {
        fetch(`https://pokeapi.co/api/v2/pokemon/?limit=27`)
            .then((res)=> res.json())
            .then((response)=> {
                this.setState({
                    isLoading: false,
                    dataSource: response.results,
                })
                console.log("RESPONSE",response)
                console.log("RESPONSE.RESSSULTS",response.results)
            })

    }

    render() {

        const showIndicator = this.state.isLoading == true ? <ActivityIndicator size="large" color="#0000ff" /> : null;
        return(
            <View style={GlobalStyles.container}>
                <SearchBarComponent style={GlobalStyles.searchBar}/>
                <PokeBanner/>
                <View style={GlobalStyles.activityIndicator}>{showIndicator}</View>
                <View style={GlobalStyles.pokeFlatList}>
                <FlatList
                    contentContainerStyle={{flexDirection: "row",justifyContent:"center", alignItems:"center"}}
                    keyExtractor={(item, index) => item.name}
                    numColumns={3}
                    data={this.state.dataSource} 
                    renderItem={({item})=> 
                    <View style={{flex: 1, flexDirection: "column", margin: 1}}>
                    <TouchableOpacity onPress={()=> this.props.navigation.navigate('PokeDetails', 
                    {item ,imageUrl: `https://projectpokemon.org/images/normal-sprite/${item.name}.gif`})}>
                        <PokeDetails imageUrl={`https://projectpokemon.org/images/normal-sprite/${item.name}.gif`} name={item.name}/>
                    </TouchableOpacity>
                    </View>
                    }/>
                </View>
                <Button onPress={()=> this.props.navigation.navigate("About")} title="Go to about"/>
            </View>
        )
    }
}


export default Home;

Это то, что происходит, когда я пытаюсь добавить contentContainerStyle, используя код ниже

enter image description here

import React, { useState } from "react";
import { View, Text , Button, FlatList, ActivityIndicator, TouchableOpacity } from "react-native";
import { GlobalStyles } from "../styles/GlobalStyles";
import PokeDetails from "./PokeDetails";
import SearchBarComponent from "../components/SearchBar";
import PokeBanner from "../components/PokeBanner";

class Home extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            isLoading: true,
            dataSource: [],
        }
    }

    componentDidMount() {
        fetch(`https://pokeapi.co/api/v2/pokemon/?limit=27`)
            .then((res)=> res.json())
            .then((response)=> {
                this.setState({
                    isLoading: false,
                    dataSource: response.results,
                })
                console.log("RESPONSE",response)
                console.log("RESPONSE.RESSSULTS",response.results)
            })

    }

    render() {

        const showIndicator = this.state.isLoading == true ? <ActivityIndicator size="large" color="#0000ff" /> : null;
        return(
            <View style={GlobalStyles.container}>
                <SearchBarComponent style={GlobalStyles.searchBar}/>
                <PokeBanner/>
                <View style={GlobalStyles.activityIndicator}>{showIndicator}</View>
                <View style={GlobalStyles.pokeFlatList}>
                <FlatList
                    contentContainerStyle={{justifyContent:"center", alignItems:"center"}}
                    keyExtractor={(item, index) => item.name}
                    numColumns={3}
                    data={this.state.dataSource} 
                    renderItem={({item})=> 
                    <View style={{flex: 1, flexDirection: "column", margin: 1}}>
                    <TouchableOpacity onPress={()=> this.props.navigation.navigate('PokeDetails', 
                    {item ,imageUrl: `https://projectpokemon.org/images/normal-sprite/${item.name}.gif`})}>
                        <PokeDetails imageUrl={`https://projectpokemon.org/images/normal-sprite/${item.name}.gif`} name={item.name}/>
                    </TouchableOpacity>
                    </View>
                    }/>
                </View>
                <Button onPress={()=> this.props.navigation.navigate("About")} title="Go to about"/>
            </View>
        )
    }
}


export default Home;

Ответы [ 2 ]

0 голосов
/ 29 апреля 2020

Для этого вы можете использовать FlatList columnWrapperStyle и удалить flex: 1 из вашего View

изменить:

                    <FlatList
                    contentContainerStyle={{justifyContent:"center", alignItems:"center"}}
                    keyExtractor={(item, index) => item.name}
                    numColumns={3}
                    data={this.state.dataSource} 
                    renderItem={({item})=> 
                    <View style={{flex: 1, flexDirection: "column", margin: 1}}>
                    <TouchableOpacity onPress={()=> this.props.navigation.navigate('PokeDetails', 
                    {item ,imageUrl: `https://projectpokemon.org/images/normal-sprite/${item.name}.gif`})}>
                        <PokeDetails imageUrl={`https://projectpokemon.org/images/normal-sprite/${item.name}.gif`} name={item.name}/>
                    </TouchableOpacity>
                    </View>
                    }/>

на

                    <FlatList 
                    columnWrapperStyle={{  flex: 1,justifyContent: "space-around"}}
                    keyExtractor={(item, index) => item.name}
                    numColumns={3}
                    data={this.state.dataSource} 
                    renderItem={({item})=> 
                    <View style={{ flexDirection: "column", margin: 1}}>
                    <TouchableOpacity onPress={()=> this.props.navigation.navigate('PokeDetails', 
                    {item ,imageUrl: `https://projectpokemon.org/images/normal-sprite/${item.name}.gif`})}>
                        <PokeDetails imageUrl={`https://projectpokemon.org/images/normal-sprite/${item.name}.gif`} name={item.name}/>
                    </TouchableOpacity>
                    </View>
                    }/>

enter image description here

Надеюсь, это поможет!

0 голосов
/ 29 апреля 2020

Единственное, что вам нужно сделать, это изменить стиль renderItem FlatList с

<View style={{flex: 1, flexDirection: "column", margin: 1}}>

на

<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', margin: 1 }}>

, также удалить contentContainerStyle из FlatList.

Для получения дополнительной информации проверьте приведенный ниже рабочий пример ( удалите некоторый код, чтобы сделать минимальный рабочий пример )

import React from "react";
import { View, FlatList, Image, Text } from "react-native";

export default class Home extends React.Component {
  state = {
    isLoading: true,
    dataSource: [],
  };

  componentDidMount() {
    fetch(`https://pokeapi.co/api/v2/pokemon/?limit=27`)
      .then((res) => res.json())
      .then((response) => {
        this.setState({
          isLoading: false,
          dataSource: response.results,
        });
      });
  }

  render() {
    return (
      <View>
        <FlatList
          data={this.state.dataSource}
          keyExtractor={(item) => item.name}
          numColumns={3}
          renderItem={({ item }) => 
            <View style={{flex: 1, justifyContent: "center", alignItems: "center", margin: 1}}>
              <Image
                source={{uri: `https://projectpokemon.org/images/normal-sprite/${item.name}.gif`}}
                style={{ width: 75, height: 75 }}
              />
              <Text>{item.name}</Text>
            </View>
          }
        />
      </View>
    );
  }
}

Надеюсь, это поможет вам. Не стесняйтесь сомнений.

...