最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use justifyContent and alignItems in react native flatlist with either contentContainerStyle etc - Stack Ove

programmeradmin1浏览0评论

I am using react native. Now, when I try to center the flatlist in the center of the screen with either specifically giving the flatlist with justifyContent and alignItems, it gives me a weird action. Also, contentContainerStyle with justifyContent and alignItems as center also gives an weird action. Been searching all day yestarday for solution. I will provide code and image below. Thank you.

im trying to align this flatlist in the center just like justfyContent and alignItems would do. You can see that the content leans towards the left of the screen.

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 "../ponents/SearchBar";
import PokeBanner from "../ponents/PokeBanner";

class Home extends React.Component {

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

    ponentDidMount() {
        fetch(`/?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: `/${item.name}.gif`})}>
                        <PokeDetails imageUrl={`/${item.name}.gif`} name={item.name}/>
                    </TouchableOpacity>
                    </View>
                    }/>
                </View>
                <Button onPress={()=> this.props.navigation.navigate("About")} title="Go to about"/>
            </View>
        )
    }
}


export default Home;

This is what happens when I try to add contentContainerStyle using the code below

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 "../ponents/SearchBar";
import PokeBanner from "../ponents/PokeBanner";

class Home extends React.Component {

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

    ponentDidMount() {
        fetch(`/?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: `/${item.name}.gif`})}>
                        <PokeDetails imageUrl={`/${item.name}.gif`} name={item.name}/>
                    </TouchableOpacity>
                    </View>
                    }/>
                </View>
                <Button onPress={()=> this.props.navigation.navigate("About")} title="Go to about"/>
            </View>
        )
    }
}


export default Home;

I am using react native. Now, when I try to center the flatlist in the center of the screen with either specifically giving the flatlist with justifyContent and alignItems, it gives me a weird action. Also, contentContainerStyle with justifyContent and alignItems as center also gives an weird action. Been searching all day yestarday for solution. I will provide code and image below. Thank you.

im trying to align this flatlist in the center just like justfyContent and alignItems would do. You can see that the content leans towards the left of the screen.

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 "../ponents/SearchBar";
import PokeBanner from "../ponents/PokeBanner";

class Home extends React.Component {

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

    ponentDidMount() {
        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/images/normal-sprite/${item.name}.gif`})}>
                        <PokeDetails imageUrl={`https://projectpokemon/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;

This is what happens when I try to add contentContainerStyle using the code below

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 "../ponents/SearchBar";
import PokeBanner from "../ponents/PokeBanner";

class Home extends React.Component {

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

    ponentDidMount() {
        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/images/normal-sprite/${item.name}.gif`})}>
                        <PokeDetails imageUrl={`https://projectpokemon/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;
Share Improve this question asked Apr 29, 2020 at 16:50 UI DeveloperUI Developer 1771 gold badge7 silver badges16 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

For this you can use FlatList columnWrapperStyle and remove flex:1 from your View

change:

                    <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/images/normal-sprite/${item.name}.gif`})}>
                        <PokeDetails imageUrl={`https://projectpokemon/images/normal-sprite/${item.name}.gif`} name={item.name}/>
                    </TouchableOpacity>
                    </View>
                    }/>

to

                    <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/images/normal-sprite/${item.name}.gif`})}>
                        <PokeDetails imageUrl={`https://projectpokemon/images/normal-sprite/${item.name}.gif`} name={item.name}/>
                    </TouchableOpacity>
                    </View>
                    }/>

Hope this helps!

The only thing you have to do is change the style of renderItem of FlatList from,

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

to

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

also remove your contentContainerStyle from FlatList.

For more information check below working example (remove some code to make a minimum working example)

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

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

  ponentDidMount() {
    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/images/normal-sprite/${item.name}.gif`}}
                style={{ width: 75, height: 75 }}
              />
              <Text>{item.name}</Text>
            </View>
          }
        />
      </View>
    );
  }
}

Hope this helps you. Feel free for doubts.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论