【发布时间】:2019-01-27 13:38:57
【问题描述】:
我的应用中有一个聊天消息列表,其中底部添加了新项目。我使用了另一个 SO question 中的一些代码来使 FlatList 在添加新项目时粘在底部,如下所示
<FlatList
data={messages}
renderItem={({item}) => <ChatMessage message={item}></ChatMessage>}
keyExtractor={(item, index) => index.toString()}
initialNumToRender={messages.length}
initialScrollIndex={messages.length-1}
ref={ref => this.flatList = ref}
onContentSizeChange={(contentWidth, contentHeight)=>{
this.flatList.scrollToEnd();
}}
/>
问题在于,当初始列表呈现(只有 35 个项目,目前在数组中硬编码)时,它似乎只呈现几个项目,然后向下滚动一点,然后再渲染一些,然后向下滚动一点直到它最终完成渲染并粘在底部。尽管添加了 initialNumToRender={messages.length} 并为每个结果渲染了一个非常简单的节点,但它还是不稳定且缓慢。
理想情况下,我想我需要等待它完全呈现,然后再向用户显示任何内容,但是 (A) 他们必须等待几秒钟才能开始使用聊天室,并且 (B) 我不认为这就是 Flatlist 的工作原理,我假设元素必须在呈现之前是可见的。
有没有更好的方法来做到这一点? (顺便在Android上测试)
编辑:为完整性添加 ChatMessage 组件
// Chat Message
import React, { Component } from 'react'
import {
StyleSheet,
ImageBackground,
Text,
View
} from 'react-native'
class ChatMessage extends Component {
constructor(props) {
super(props)
this.state = { }
}
render() {
return (
<View style={styles.chatMessage}>
<View style={styles.chatMessage_layout}>
<View style={styles.chatMessage_pic}>
<View style={styles.chatMessage_pic_image}>
<ImageBackground
source={require('./assets/images/profile-pics/example-profilr.png')}
style={styles.chatMessage_pic_image_background}
imageStyle={{ borderRadius: 40/2 }}
resizeMode="cover"
>
</ImageBackground>
</View>
</View>
<View style={styles.chatMessage_details}>
<View style={styles.chatMessage_name}>
<Text style={styles.chatMessage_name_text}>
{this.props.message.name}
<Text style={styles.chatMessage_name_time}> 24h</Text>
</Text>
</View>
<View style={styles.chatMessage_message}>
<Text style={styles.chatMessage_message_text}>{this.props.message.text}</Text>
</View>
</View>
</View>
</View>
)
}
}
export default ChatMessage;
const styles = StyleSheet.create({
chatMessage: {
paddingVertical: 10,
paddingHorizontal: 24
},
chatMessage_layout: {
flexDirection: 'row'
},
chatMessage_pic: {
width: 40,
height: 40,
marginRight: 12
},
chatMessage_pic_image: {
width: 40,
height: 40
},
chatMessage_pic_image_background: {
width: 40,
height: 40
},
chatMessage_details: {
flex: 1
},
chatMessage_name_text: {
color: '#FFF',
fontSize: 14,
fontWeight: 'bold'
},
chatMessage_name_time: {
fontSize: 11,
color: 'rgba(255,255,255,0.6)'
},
chatMessage_message: {
flexDirection: 'row',
alignItems: 'center'
},
chatMessage_message_text: {
color: '#FFF',
fontSize: 12
}
})
【问题讨论】:
-
你也可以发布你的
ChatMessage组件吗? -
在github.com/FaridSafi/react-native-gifted-chat中,他使用列表从下往上渲染。
-
添加子组件
-
谢谢@Kranthi,会调查的。
标签: react-native