【问题标题】:FlatList not rendering rowFlatList 不呈现行
【发布时间】:2020-01-07 13:07:40
【问题描述】:

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

App.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

ColorButton.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-native react-native-flatlist


    【解决方案1】:

    将您的平面列表代码更改为以下代码:

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

    希望对您有所帮助。如有疑问,请随意

    【讨论】:

    • 嗨 Gaurav,我修改了下面的代码,它工作了。您的建议的一个小改动 ( )} /> 感谢您的帮助。
    • 很高兴它有帮助:)
    猜你喜欢
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-31
    • 2019-03-17
    相关资源
    最近更新 更多