首页 > 解决方案 > FlatList 不呈现行

问题描述

我正在尝试学习 react-native 的 FlatList 组件。观察一个教程,我实现了一个示例应用程序,它列出了滚动视图中的组件。我正在尝试用 FlatList 替换滚动视图,但项目不是屏幕上的渲染。我在这里包含了主要的源代码。

应用程序.js

import React, { Component } from 'react'
import {
  StyleSheet,
  View,
  ScrollView,
  FlatList
} from 'react-native'
import ColorButton from './components/ColorButton'

class App extends Component {

  constructor() { 
    super()
    this.state = {
      backgroundColor: 'blue'
    }

    this.changeColor = this.changeColor.bind(this)
  }

  changeColor(backgroundColor) {
    this.setState({backgroundColor})
  }

  render() {
    const { backgroundColor } = this.state
    return(
      <FlatList 
        data = {'red', 'green', 'salmon'} 
        renderItem = {(color) => {
          <ColorButton backgroundColor={color} onSelect={this.changeColor}></ColorButton>
        } } />
    )
  }
}

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

export default App

颜色按钮.js

import React from 'react'
import {
    StyleSheet,
    Text,
    View,
    TouchableHighlight
} from 'react-native'

const ColorButton = ({ backgroundColor, onSelect=f=>f }) => (
    <TouchableHighlight 
        style = {styles.button} 
        onPress={() => onSelect(backgroundColor)} 
        underlayColor="orange">

        <View style = {styles.row}>
            <View style = {[styles.sample, {backgroundColor}]} />
            <Text style = {styles.text}>backgroundColor</Text>
        </View>
    </TouchableHighlight>
)

const styles = StyleSheet.create({
    button: {
      margin: 10,
      padding: 10,
      borderWidth: 2,
      borderRadius: 10,
      alignSelf: 'stretch',
      backgroundColor: 'rgba(255,255,255,0.8)'
    },
    row: {
      flexDirection: 'row',
      alignItems: 'center'
    },
    sample: {
      height: 20,
      width: 20,
      borderRadius: 10,
      margin: 5,
      backgroundColor: 'white'
    },
    text: {
      fontSize: 30,
      margin: 5
    }
  })

  export default ColorButton

标签: react-nativereact-native-flatlist

解决方案


将您的 flatlist 代码更改为以下代码:

   <FlatList 
    data = {['red', 'green', 'salmon']} 
    renderItem = {({item}) => {
      <ColorButton backgroundColor={item} onSelect={this.changeColor}> 
    </ColorButton>
    } } />

希望能帮助到你。随时怀疑


推荐阅读