在 React Native 中动态添加项目到 FlatList

我有一个包含两个项目的 FlatList。我需要在这个列表中附加其他元素。当用户单击按钮时,来自文本输入的数据应出现在 FlatList 的末尾。因此,我尝试将数据对象推送到列表数组的末尾,但新项目替换了最后一个。


import React, { useState } from 'react';

import { Text, View, StyleSheet, Button } from 'react-native';

import { FlatList } from 'react-native-gesture-handler';


export default function HomeScreen() {


  var initialElements = [

    { id : "0", text : "Object 1"},

    { id : "1", text : "Object 2"},

  ]


  const [exampleState, setExampleState] = useState(initialElements);

  const [idx, incr] = useState(2);


  const addElement = () => {

    var newArray = [...initialElements , {id : toString(idx), text: "Object " + (idx+1) }];

    initialElements.push({id : toString(idx), text: "Object " + (idx+1) });

    incr(idx + 1);

    setExampleState(newArray);

  }


  return (

    <View style={styles.container}>

        <FlatList

            keyExtractor = {item => item.id}  

            data={exampleState}

            renderItem = {item => (<Text>{item.item.text}</Text>)} />

        <Button

          title="Add element"

          onPress={addElement} />

    </View>

  );

}


const styles = StyleSheet.create({

  container: {

    flex: 1,

    backgroundColor: '#fff',

    width: '100%',

    borderWidth: 1

  },

});


阿晨1998
浏览 188回答 3
3回答

慕姐8265434

import React, { useState } from 'react';import { Text, View, StyleSheet, Button } from 'react-native';import { FlatList } from 'react-native-gesture-handler';export default function HomeScreen() {&nbsp; var initialElements = [&nbsp; &nbsp; { id : "0", text : "Object 1"},&nbsp; &nbsp; { id : "1", text : "Object 2"},&nbsp; ]&nbsp; const [exampleState, setExampleState] = useState(initialElements)&nbsp; const addElement = () => {&nbsp; &nbsp; var newArray = [...initialElements , {id : "2", text: "Object 3"}];&nbsp; &nbsp; setExampleState(newArray);&nbsp; }&nbsp; return (&nbsp; &nbsp; <View style={styles.container}>&nbsp; &nbsp; &nbsp; &nbsp; <FlatList&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; keyExtractor = {item => item.id}&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data={exampleState}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; renderItem = {item => (<Text>{item.item.text}</Text>)} />&nbsp; &nbsp; &nbsp; &nbsp; <Button&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; title="Add element"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onPress={addElement} />&nbsp; &nbsp; </View>&nbsp; );}const styles = StyleSheet.create({&nbsp; container: {&nbsp; &nbsp; flex: 1,&nbsp; &nbsp; backgroundColor: '#fff',&nbsp; &nbsp; width: '100%',&nbsp; &nbsp; borderWidth: 1&nbsp; },});您只是在更改 listElements 数组。这不会触发组件的重新渲染,因此平面列表将保持不变。在组件中创建一个状态变量并将您的数据存储在其中,以便任何修改都会导致重新渲染。

千万里不及你

我通过在导出函数之外定义数组来修复它import React, { useState } from 'react'import { StyleSheet, View, TextInput, TouchableOpacity, Text, FlatList } from 'react-native'let tipArray = [&nbsp; &nbsp; {key: '1', tip: 20},&nbsp; &nbsp; {key: '2', tip: 12}]const screen = function tipInputScreen( {navigation} ) {&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; const [ tip, setTip ] = useState('')&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; const addTip = ()=>{&nbsp; &nbsp; &nbsp; &nbsp; if(tip == "")return&nbsp; &nbsp; &nbsp; &nbsp; tipArray.push({key: (tipArray.length + 1).toString(), tip})&nbsp; &nbsp; &nbsp; &nbsp; setTip('')&nbsp; &nbsp; }&nbsp; &nbsp; const logInput = (input)=>{&nbsp; &nbsp; &nbsp; &nbsp; setTip(input)&nbsp; &nbsp; }&nbsp; &nbsp; const renderTip = ({ item }) => {&nbsp; &nbsp; &nbsp; &nbsp; return(&nbsp; &nbsp; &nbsp; &nbsp; <TouchableOpacity style={styles.listItem}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Text style={styles.buttonText}>{`${item.tip} $`}</Text>&nbsp; &nbsp; &nbsp; &nbsp; </TouchableOpacity>)&nbsp; &nbsp; }&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; <View&nbsp; &nbsp; &nbsp; &nbsp; style={styles.background}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <TextInput&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; style={styles.input}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; keyboardType={'number-pad'}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; keyboardAppearance={'dark'}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onChangeText={logInput}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value={tip}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <TouchableOpacity&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; style={styles.redButton}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onPress={addTip}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Text style={styles.buttonText}>Add Tip</Text>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </TouchableOpacity>&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <FlatList&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data={tipArray}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; renderItem={renderTip}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; style={styles.flatList}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; &nbsp; &nbsp; </View>&nbsp; &nbsp; )}const styles = StyleSheet.create({&nbsp; &nbsp; background: {&nbsp; &nbsp; &nbsp; &nbsp; backgroundColor: 'grey',&nbsp; &nbsp; &nbsp; &nbsp; paddingTop: Platform.OS === "android" ? 25:0,&nbsp; &nbsp; &nbsp; &nbsp; width: '100%',&nbsp; &nbsp; &nbsp; &nbsp; height: '100%',&nbsp; &nbsp; &nbsp; &nbsp; alignItems: 'center'&nbsp; &nbsp; },&nbsp; &nbsp; input: {&nbsp; &nbsp; &nbsp; &nbsp; marginTop:40,&nbsp; &nbsp; &nbsp; &nbsp; color:'white',&nbsp; &nbsp; &nbsp; &nbsp; fontSize:30,&nbsp; &nbsp; &nbsp; &nbsp; backgroundColor: "#2e2a2a",&nbsp; &nbsp; &nbsp; &nbsp; height: 50,&nbsp; &nbsp; &nbsp; &nbsp; width: '90%',&nbsp; &nbsp; &nbsp; &nbsp; textDecorationColor: "white",&nbsp; &nbsp; &nbsp; &nbsp; borderColor: 'black',&nbsp; &nbsp; &nbsp; &nbsp; borderWidth: 2&nbsp; &nbsp; },&nbsp; &nbsp; flatList:{&nbsp; &nbsp; &nbsp; &nbsp; width: "100%"&nbsp; &nbsp; },&nbsp; &nbsp; listItem: {&nbsp; &nbsp; &nbsp; &nbsp; width: "90%",&nbsp; &nbsp; &nbsp; &nbsp; height: 50,&nbsp; &nbsp; &nbsp; &nbsp; backgroundColor: "#2e2e2e",&nbsp; &nbsp; &nbsp; &nbsp; borderRadius: 25,&nbsp; &nbsp; &nbsp; &nbsp; marginVertical: 4,&nbsp; &nbsp; &nbsp; &nbsp; marginHorizontal: "5%",&nbsp; &nbsp; &nbsp; &nbsp; justifyContent: "center"&nbsp; &nbsp; },&nbsp; &nbsp; listItemTitle: {&nbsp; &nbsp; &nbsp; &nbsp; color: "white",&nbsp; &nbsp; &nbsp; &nbsp; textAlign: "center",&nbsp; &nbsp; &nbsp; &nbsp; fontSize: 18&nbsp; &nbsp; },&nbsp; &nbsp; redButton: {&nbsp; &nbsp; &nbsp; &nbsp; justifyContent: "center",&nbsp; &nbsp; &nbsp; &nbsp; width: "90%",&nbsp; &nbsp; &nbsp; &nbsp; height: 50,&nbsp; &nbsp; &nbsp; &nbsp; backgroundColor: "red",&nbsp; &nbsp; &nbsp; &nbsp; borderRadius: 25,&nbsp; &nbsp; &nbsp; &nbsp; marginHorizontal: 20,&nbsp; &nbsp; &nbsp; &nbsp; marginVertical: 10&nbsp; &nbsp; },&nbsp; &nbsp; buttonText: {&nbsp; &nbsp; &nbsp; &nbsp; color: "white",&nbsp; &nbsp; &nbsp; &nbsp; textAlign: "center",&nbsp; &nbsp; &nbsp; &nbsp; fontSize: 18&nbsp; &nbsp; }})export default screen;这是一个更大的应用程序的一部分,但它应该可以解决问题,我希望它有所帮助

紫衣仙女

我通过将数组更改为状态变量来解决替换元素的问题。import React, { useState } from 'react';import { Text, View, StyleSheet, Button } from 'react-native';import { FlatList } from 'react-native-gesture-handler';export default function HomeScreen() {&nbsp; const [initialElements, changeEl]&nbsp; = useState([&nbsp; &nbsp; { id : "0", text : "Object 1"},&nbsp; &nbsp; { id : "1", text : "Object 2"},&nbsp; ]);&nbsp; const [exampleState, setExampleState] = useState(initialElements);&nbsp; const [idx, incr] = useState(2);&nbsp; const addElement = () => {&nbsp; &nbsp; var newArray = [...initialElements , {id : idx, text: "Object " + (idx+1) }];&nbsp; &nbsp; incr(idx + 1);&nbsp; &nbsp; console.log(initialElements.length);&nbsp; &nbsp; setExampleState(newArray);&nbsp; &nbsp; changeEl(newArray);&nbsp; }&nbsp; return (&nbsp; &nbsp; <View style={styles.container}>&nbsp; &nbsp; &nbsp; &nbsp; <FlatList&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; keyExtractor = {item => item.id}&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data={exampleState}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; renderItem = {item => (<Text>{item.item.text}</Text>)} />&nbsp; &nbsp; &nbsp; &nbsp; <Button&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; title="Add element"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onPress={addElement} />&nbsp; &nbsp; </View>&nbsp; );}const styles = StyleSheet.create({&nbsp; container: {&nbsp; &nbsp; flex: 1,&nbsp; &nbsp; backgroundColor: '#fff',&nbsp; &nbsp; width: '100%',&nbsp; &nbsp; borderWidth: 1&nbsp; },});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript