首页 文章

如何从TextInput填充Flatlist

提问于
浏览
0

我正在尝试使用来自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

    仅当 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

  • 0

    变化: onChangeText={this._handleIngredients}

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

    这是为了保留 this 的范围 .

相关问题