【问题标题】:How to get the value ot TextInput and add to Flatlist in React Native如何在 React Native 中获取 Text Input 的值并添加到 Flatlist
【发布时间】:2021-04-18 16:39:33
【问题描述】:

我想获取 TextInput 的值并添加到我的 flatList: 这是我的文本输入


        <TextInput style={styles.input}
          underlineColorAndroid="transparent"
          placeholder="   Money "
          placeholderTextColor="#9a73ef"
          autoCapitalize="none"
          keyboardType='numeric'
          value = 'money'
        />

这是我的按钮,它将 TextInput 的值添加到我的平面列表中

 <Button
          title="Add me"
          color="#841584"
          accessibilityLabel="Learn more about this purple button"
        />

        <FlatList
          data={DATA}
          renderItem={({ item }) => (<Text style = {styles.item}> {item.name}</Text>)} />


    </View>

【问题讨论】:

  • 我是新来的,请大家帮忙

标签: javascript java reactjs react-native


【解决方案1】:

工作示例:Expo Snack

import React, { useState } from 'react';
import {
  Text,
  View,
  StyleSheet,
  TextInput,
  Button,
  FlatList,
} from 'react-native';
import Constants from 'expo-constants';

export default function App() {
  const [data, setData] = useState([{ name: 'ketan' }]);
  const [name, setName] = useState('');
  return (
    <View style={styles.container}>
      <TextInput
        style={{ backgroundColor: 'white', padding: 10, marginTop: 10 }}
        onChangeText={(name) => setName(name)}
        placeholder={'enter name'}
        value={name}
      />
      <Button
        title={'add me'}
        onPress={() => {
          if (name) setData([...data, { name: name }]);
          console.log('hi');
        }}
      />
      <FlatList
        keyExtractor={(item) => item}
        data={data}
        renderItem={({ item }) => <Text>{item.name}</Text>}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
});

【讨论】:

  • 如果我有 Picker 我如何将其插入平面列表?
  • 请编写您尝试过的代码,如果您遇到任何问题或想要实现某些您无法实现的行为,请发布有关它的问题。我或社区中的其他人很乐意为您提供帮助:)
【解决方案2】:

刚刚添加

 <FlatList
          data={data}
          renderItem={({ item }) => (<Text style = {styles.item}> {item.name}</Text>)}
          keyExtractor={(item, index) => index.toString()}  
           />

成功了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    相关资源
    最近更新 更多