FlatList не рендеринг строки - PullRequest
1 голос
/ 07 января 2020

Я пытаюсь выучить FlatList компонентом Reaction-native. Наблюдая за учебником, я реализовал примеры приложений, в которых перечисляются компоненты внутри прокрутки. Я пытаюсь заменить scrollview на 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

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

1 Ответ

4 голосов
/ 07 января 2020

Измените свой код для плоского списка на следующий:

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

Надеюсь, это поможет. не стесняйтесь сомнений

...