首页 > 解决方案 > React-native flatlist 不渲染?

问题描述

我的 ReactNative FlatList 没有使用这个简单的实现进行渲染。

 <FlatList style={{flex:1, backgroundColor:'red'}}
           data = {this.state.users}
           keyExtractor={item => item.key.toString()}
           renderItem={({item}) => {
               return (
                   <ChatUserCard key={item.uid} username={item.username} />
               )
           }}
/>

聊天用户卡

<View style={styles.cardStyle}> 
    <Text style={styles.itemStyle}>{this.props.username}</Text>
    <Button style={styles.buttonStyle}
            title='Chat'
            onPress={this.startChat} />
</View>

标签: javascriptreact-native

解决方案


我在想发生的事情是你没有把你的东西包裹FlatList在一个View已经flex: 1设置好的东西中。此外,您可能可以使用您的uid作为您的密钥,而不是key在您的对象数据中设置 a

演示

https://snack.expo.io/@anonymoussb/so53688423

import * as React from 'react';
import { Text, View, StyleSheet, Button, FlatList } from 'react-native';

class ChatUserCard extends React.Component {
  render() {
    return (
      <View style={styles.cardStyle}> 
          <Text style={styles.itemStyle}>{this.props.username}</Text>
          <Button style={styles.buttonStyle}
                  title='Chat'
                  onPress={this.startChat} />
      </View>
    )
  }
}

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      users: [
        { key: 123, uid: 123, username: 'taco' },
        { key: 456, uid: 456, username: 'cat' }
      ]
    }
  }
  render() {
    return (
      <View style={styles.container}>
        <FlatList style={{flex:1, backgroundColor:'red'}}
           data = {this.state.users}
           keyExtractor={item => item.key.toString()}
           renderItem={({item}) => {
               return (
                   <ChatUserCard key={item.uid} username={item.username} />
               )
           }}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
});

推荐阅读