Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

235
Visualizações
FlatList supera a su contenedor con su contenido: Cómo hacer FlatList con altura fija

Tengo una <FlatList /> . Dentro de esta <FlatList /> tengo otra <FlatList /> . El <FlatList /> anidado me da un comportamiento extraño. Excede los márgenes de su contenedor. Como puede ver, las banderas van sobre el cuadro yellow , que representa los límites de la <FlatList /> .

Aquí hay un Snack https://snack.expo.dev/@stophfacee/nested-flatlist que reproduce el problema.

Tenga en cuenta: la animación (al tocar el rectángulo hotpink ) no funciona correctamente. No estoy seguro por qué. Sin embargo, todavía lo incluí porque no estoy seguro de si ese podría ser el problema.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Este podría ser el resultado que querías. ¡Por favor revise esto una vez!

 import React, { useState } from 'react'; import { View, StyleSheet, Animated, Dimensions, TouchableOpacity, Text, ScrollView, } from 'react-native'; import Constants from 'expo-constants'; import CountryFlag from 'react-native-country-flag'; import { FlatList } from 'react-native-gesture-handler'; export default function App() { const _renderFlag = (country) => { return ( <TouchableOpacity onPress={() => console.log('Flag touched')}> <CountryFlag isoCode={'NZ'} size={50} style={{ alignSelf: 'flex-end' }} /> </TouchableOpacity> ); }; const _createCard = (card, index) => { return ( <View style={styles.card} key={index}> <TouchableOpacity style={styles.touchable} onPress={() => console.log('toggle')}> <Text>{card}</Text> </TouchableOpacity> <View style={{ height: 200 }}> <FlatList nestedScrollEnabled={true} style={{ marginTop: 20, backgroundColor: 'yellow' }} columnWrapperStyle={{ justifyContent: 'space-around', }} ItemSeparatorComponent={() => <View style={{ margin: 10 }}/>} numColumns={3} data={[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, ]} renderItem={_renderFlag} keyExtractor={(item, index) => index.toString()} getItemLayout={(data, index) => ({ length: 50, offset: 50 * index, index, })} /> </View> </View> ); }; return ( <View style={{ flex: 1 }}> <FlatList style={{ margin: 20 }} data={['a', 'b', 'c']} keyExtractor={(item, index) => index.toString()} renderItem={({ item, index }) => _createCard(item, index)} /> </View> ); } const styles = StyleSheet.create({ card: { borderColor: 'red', borderWidth: 2, padding: 8, marginBottom: 15, }, touchable: { backgroundColor: 'hotpink', height: 50, width: '100%', justifyContent: 'center', alignItems: 'center', }, });

Ejemplo de trabajo

about 4 years ago · Juan Pablo Isaza Relatório

0

No soy muy bueno con reaccionar nativo, ni puedo ver su problema, sin embargo, mencionó que está pasando por encima del contenedor. Eché un vistazo a su código y sé que en css/web normal su estilo no funcionará.

Tiene una <FlatList y le ha dado un estilo para style={styles.container} . El estilo de ese contenedor es:

 container: { paddingTop: 50, height: '100%', widht: '100%', }

Ahí le estás diciendo al contenedor que tenga una height: 100% y luego también le estás diciendo que tenga un relleno de 50. Eso dará como resultado una altura total de 100 % + 50. Para corregir eso, debes usar la height: calc(100% - 50) junto con su relleno, entonces encajará perfectamente.

No tengo idea si ese es su problema real, pero no puedo ver cómo funcionaría a menos que React Native esté haciendo algunas cosas extravagantes con el relleno.

De hecho, también has hecho esto en un par de lugares, en tu tarjeta has usado width: '90%' junto con padding: 8 , por lo que la tarjeta desbordará su contenedor con 6. Allí también debes hacer width: calc(100% - 16) .

Esto se volverá aún más confuso si tiene borderWidth: 2 y no tiene box-sizing: border-box , lo que dará como resultado que sea incluso 4 más sobre el ancho del contenedor.

Debe tener cuidado con los rellenos/bordes/etc adicionales que agrega cuando ha especificado que es 100% ancho/alto.

about 4 years ago · Juan Pablo Isaza Relatório

0

Teniendo en cuenta el consejo de Dan y AmerllicA, este es un posible uso de SectionList que parece resolver su problema:

¡No olvides importar SectionList desde react-native !

 const sections = [ { title: 'Section 1', data: ['a', 'b', 'c'].map((card, index) => _createCard(card, index)) }, { title: 'Section 2', data: ['a', 'b', 'c'].map((card, index) => _createCard(card, index)) }, { title: 'Section 3', data: ['a', 'b', 'c'].map((card, index) => _createCard(card, index)) }, ]; return ( <SectionList initialNumToRender={2} contentContainerStyle={{ alignItems: 'center' }} style={styles.container} sections={sections} renderItem={(item) => { return item.item; }} renderSectionHeader={({ section: { title } }) => ( <View style={{ backgroundColor: 'pink', width:200, alignItems: 'center', justifyContent: 'center', height: 50 }}> <Text>{title}</Text> </View> )} /> );
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda