Tengo una Flatlist que representa varias publicaciones, cada publicación tiene una sección de texto, el texto puede volverse muy grande, así que estoy usando un método para mostrar más para expandir/ocultar el texto, y estoy manejando el estado usando un estado , sin embargo, cuando hago clic en una publicación para expandir el texto, expande todas las publicaciones en Flatlist, intenté crear una Ref dinámica para cada publicación, pero no puedo encontrar una manera de cambiar el contenido del texto en consecuencia, cualquier cosa que estoy perdido?
aquí está mi código:
const [showMore, setShowMore] = useState(false); const refs = useRef([]); // Inside a Flatlist render item: <View style={styles.postContainer}> {item.data.postText.length > 120 ? ( showMore ? ( <TouchableOpacity onPress={() => setShowMore(!showMore)} ref={(expandableText) => (refs.current[index] = expandableText)}> <Text style={styles.postDescription}>{item.data.postText}</Text> <Text style={styles.seeMore}>Show less</Text> </TouchableOpacity> ) : ( <TouchableOpacity onPress={() => setShowMore(!showMore)}> <Text style={styles.postDescription}> {`${item.data.postText.slice(0, 120)}... `} </Text> <Text style={styles.seeMore}>Show more</Text> </TouchableOpacity> ) ) : ( <Text style={styles.postDescription}>{item.data.postText}</Text> )} </View>Está utilizando el mismo estado para todos los elementos de FlatList . Por lo tanto, si cambia el estado, todos los elementos se expandirán. Podría mantener una matriz booleana como estado. El índice de esta matriz de estado corresponde al índice de un componente dentro de la lista plana.
// data is the data of your FlatList // we use this to initialize each show more value with false const [showMore, setShowMore] = useState(data.map(data => false))En su función de renderizado, la usa de la siguiente manera.
renderItem={({item, index}) => { return <View style={styles.postContainer}> {item.data.postText.length > 120 ? ( showMore[index] ? ( <TouchableOpacity onPress={() => handleShowMore(index)} ref={(expandableText) => (refs.current[index] = expandableText)}> <Text style={styles.postDescription}>{item.data.postText}</Text> <Text style={styles.seeMore}>Show less</Text> </TouchableOpacity> ) : ( <TouchableOpacity onPress={() => handleShowMore(index)}> <Text style={styles.postDescription}> {`${item.data.postText.slice(0, 120)}... `} </Text> <Text style={styles.seeMore}>Show more</Text> </TouchableOpacity> ) ) : ( <Text style={styles.postDescription}>{item.data.postText}</Text> )} </View> } La función handleShowMore es la siguiente.
function handleShowMore(index) { setShowMore(prev => prev.map((element, idx) => { if(idx === index) { return !element } return element })) }