如何从TextInput填充Flatlist

时间:2018-02-12 16:55:18

标签: react-native react-native-flatlist

我正在尝试使用来自TextInput的值填充FlatList行。 您可以在下面找到我当前的代码。

import React, { Component } from 'react'
import { View, Text, TouchableOpacity, TextInput, StyleSheet, 
StatusBar, FlatList } from 'react-native'

globalText = require('../styles/Texts.js');
globalColors = require('../styles/Colors.js');

class SearchInput extends Component {
 constructor(props) {
 super(props);
 this.state = {
  data: [],
  ingredients: ''
 }
}

_handleIngredients = (text) => {
 this.setState({ ingredients: text })
}

render(){
  return (
    <View style={styles.container}>
      <StatusBar barStyle="dark-content"/>
      <View>
       <TextInput style={[globalText.btnFlatPrimary, styles.inputText]}
         underlineColorAndroid='transparent'
         placeholder='Add ingredients'
         placeholderTextColor={globalColors.lightGrey}
         autoCapitalize='sentences'
         autoCorrect={false}
         autoFocus={true}
         onChangeText={this._handleIngredients}
         keyboardShouldPersistTaps='handled'
        />
     </View>
     <FlatList
       data={this.state.data}
       renderItem={({text}) => (
         <View style={styles.cell}>
           <Text style={globalText.btnFlatPrimary}>{this.state.ingredients}</Text>
         </View>
       )}
     />
   </View>
  )
 }
}

const styles = StyleSheet.create({
 container: {
  paddingTop: 20,
  backgroundColor: globalColors.white,
 },
 inputText: {
  paddingLeft: 16,
  paddingRight: 16,
  height: 60
 },
 cell: {
  height: 60,
  paddingLeft: 16,
  justifyContent: 'center',
 }
});

export default SearchInput;

我可能遗漏了一些东西,但如果我预先填充数据和成分状态,那么FlatList会正确显示输入的值。我希望用TextInput填充Flalist

data: [{key:'a'}],
ingredients: 'tomato'

2 个答案:

答案 0 :(得分:0)

更改:onChangeText={this._handleIngredients}

至:onChangeText={(text) => this._handleIngredients(text)}

这是为了保留this的范围。

答案 1 :(得分:0)

如果data属性发生更改,则仅会重新呈现Flatlist。如果您希望它根据其他值重新渲染,则需要传递extraData道具。

<FlatList
   data={this.state.data}
   extraData={this.state.ingredients} //here
   renderItem={({text}) => (
     <View style={styles.cell}>
       <Text style={globalText.btnFlatPrimary}>{this.state.ingredients}</Text>
     </View>
   )}
 />

在此处阅读更多内容:https://facebook.github.io/react-native/docs/flatlist.html#extradata