React Native FlatList with columns,Last item width

时间:2017-04-19 17:59:10

标签: react-native react-native-flatlist

我正在使用FlatList来显示两列中的项目列表

<FlatList style={{margin:5}}
  data={this.state.items}
  numColumns={2}
  keyExtractor={(item, index) => item.id }
  renderItem={(item) => <Card image={item.item.gallery_image_url} text={item.item.name}/> }
/>

卡组件只是一个具有某些样式的视图:

<View style={{ flex: 1, margin: 5, backgroundColor: '#ddd', height: 130}} ></View>

工作正常,但如果项目数是奇数,则最后一行只包含一个项目,该项目会延伸到屏幕的整个宽度。

如何将项目设置为与其他项目相同的宽度?

enter image description here

10 个答案:

答案 0 :(得分:19)

你可以尝试一些事情。

A)设置卡片的预定义宽度(可能等于您设置的高度?)。然后您可以使用alignItems将卡片放在中间或左侧 - 不确定您想要的位置。

B)如果卡数为偶数,您可以在末尾添加一个空视图以填充此空间。我发现这种方法非常笨重,但在为未来的元素留出空间时非常有用。

C)只需使用alignItems: 'space-between,我喜欢用它来居中项目,但您必须定义宽度,或使用类似flex:0.5

的内容

我建议更多地研究一下flexbox来帮助你解决这个问题,因为很难说清楚这种情况。我假设上述方法会有所帮助,但如果没有,这里有一些链接供您查看 -

First link

Second link

Third link Link Broken

希望这会有所帮助。如果您需要进一步澄清 - 请询问

答案 1 :(得分:14)

您可以尝试通过Dimensions获取设备的当前宽度,根据要渲染的列数进行一些计算,减去边距并将其设置为minWidth和maxWidth。

例如:

const {height, width} = Dimensions.get('window');
const itemWidth = (width - 15) / 2;

<View style={{ flex: 1, margin: 5, backgroundColor: '#ddd', minWidth: {this.itemWidth}, maxWidth: {this.itemWidth}, height: 130}} ></View>

答案 2 :(得分:12)

根据您的情况使用 flex:1/2

因此:您的项目 flex 应该为1 /(列数),如果您有3列,则您的项目应具有flex:1/3

答案 3 :(得分:1)

@Emilius Mfuruki的建议很好,但是如果文本的长度不同,则效果不理想。然后在项目视图中使用以下宽度:

const {height, width} = Dimensions.get('window');
const itemWidth = (width - (MarginFromTheSide * 2 + MarginInBetween * (n-1))) / n;

在FlatList中使用:

columnWrapperStyle={{
            flex: 1,
            justifyContent: 'space-evenly',
          }}

完美运行。

答案 4 :(得分:0)

检查项数是否为奇数,如果数为奇数,请为最后一项赋予特殊样式。 例如)

from flask import Flask, request, render_template
from werkzeug import secure_filename
import pandas as pd
app = Flask(__name__)

@app.route('/upload')
def upload():
    return render_template('upload.html')

@app.route('/uploader',methods = ['GET','POST'])
def uploader():
    if request.method == 'POST':
        #f = request.files['file']
        df = pd.read_csv(request.files.get('file'))
        #f.save(secure_filename(f.filename))
        #df = pd.DataFrame(eval(f))
        return print(df.shape)

if __name__ == '__main__':
    app.run(debug = True)

答案 5 :(得分:0)

其原因是您的卡具有样式flex: 1,因此它将尝试扩大所有剩余空间。 您可以通过在卡片样式中添加maxWidth: '50%'来解决此问题

<View style={{ flex: 1, margin: 5, backgroundColor: '#ddd', height: 130, maxWidth: '50%'}} ></View>

答案 6 :(得分:0)

这是最简单的设置FlatList样式的方法,该方法使用列并均匀隔开:

    <FlatList style={{margin:5}}
        numColumns={2}                  // set number of columns 
        columnWrapperStyle={style.row}  // space them out evenly

        data={this.state.items}
        keyExtractor={(item, index) => item.id }
        renderItem={(item) => <Card image={item.item.gallery_image_url} text={item.item.name}/> }
    />       

    const style = StyleSheet.create({
        row: {
            flex: 1,
            justifyContent: "space-around"
        }
    });

答案 7 :(得分:0)

您可以使用ListFooterComponent = {this.renderFooter}

答案 8 :(得分:0)

只需使用flex:0.5和width:'50%'

答案 9 :(得分:0)

创建一个包含奇数个图像的数组,例如:

const images = [
  require('./../...jpg'),
  require('./../...jpg'),
  require('./../...jpg'),
  require('./../...jpg'),
  require('./../...jpg'),
];

然后,使用下面给出的代码,

const App = () => {
const _renderItem = ({ item, index }) => (
  <Image
    source={item}
    style={{
      width:
        images.length % 2 !== 0 && images.length - 1 === index
          ? '100%'
          : '50%',
      height: 200,
    }}
    resizeMode="cover"
  />
 );

return (
    <View style={{flex: 1, marginHorizontal: 10,}}>
      <FlatList
        columnWrapperStyle={{ justifyContent: 'space-between' }}
        data={images}
        numColumns={2}
        renderItem={_renderItem}
      />
    </View>
  )
};
export default App;

Working Example