如何在React Native Expo中按下按钮时更新FlatList?

f87krz0w  于 2023-10-22  发布在  React
关注(0)|答案(1)|浏览(152)
export default function App() {
  const [toDoList, setToDoList] = React.useState([
    { task:'dishes', id:'1'},
    { task:'laundry', id:'2'},
    { task:'dishes', id:'3'},
    { task:'laundry', id:'4'},
    { task:'dishes', id:'5'},
  ])

  const [inputText, setText] = React.useState('');

  return (
    <View style={styles.container}>
      <TextInput
        style={styles.input}
        onChangeText={newText => setText(newText)}
        value={inputText}
        placeholder='Input Task'
      />
      
      <TouchableOpacity onPress={() => {
        index = toDoList.length + 1
        toDoList.push({ task: {inputText}, id:{index} })
        setToDoList(...toDoList)
      }}>
        <Text style={styles.item}>Add Task</Text> 
      </TouchableOpacity>
      
      <FlatList
      data={toDoList}
      extraData={toDoList}
      renderItem= {({ item }) => ( <Text style={ styles.item }>{item.task}</Text>)}/>
    </View>
  );
}

我希望它在单击“AddItem”按钮时向平面列表添加一个新项,并且它应该从TextInput组件获取任务。然而,当我尝试它时,它不会以任何方式更新FlatList。为什么会这样?我认为这可能是一个问题,与toDoList没有正确更新,但我不确定。

rjjhvcjd

rjjhvcjd1#

<TouchableOpacity onPress={() => {
    let index = toDoList.length + 1;
    let newTask = { task: `${inputText}`, id: index };
    setToDoList([...toDoList, newTask])
}}>
    <Text style={styles.item}>Add Task</Text> 
</TouchableOpacity>

相关问题