首页 > 解决方案 > 仅更改对象列表中的一个图标 - React Native

问题描述

我希望能够将待办事项列表(见图)中的图标从感叹号更改为复选标记。如果用户将手指放在图标上,或者开发人员在模拟器中用鼠标单击,就会发生这种情况。

通过下面的代码,我设法对其进行了更改,但是仅当我关闭包含列表的模式并重新打开它时,才会出现新图标。所以模态不会重新渲染,既不是部分也不是全部。

如何在单击感叹号图标后立即显示更改?我怀疑它与状态有关,但似乎不可能在 map 函数中创建一个 React 钩子。如果我让 onPress 调用一个函数,那么状态只能在那个外部函数中知道,我不知道如何导出它。

export const TeacherMessages = (props) => {
  return (
    <View
        style={[
        styles.borderBox,
        props.todos.length > 0 || props.notes.length > 0
            ? styles.whiteBox
            : null,
        ]}
    >
        {
            props.todos.map((todo) => (
                <View key={todo.id} style={styles.listNotes}>
                  <AntDesign
                      style={styles.listIcon}
                      onPress={() => todo.isChecked = true}
                      name={todo.isChecked ? "checksquare" : "exclamationcircle"}
                      color={todo.isChecked ? "green" : "red"}
                      size={18}
                  />
                  <Text style={styles.listText}> {todo.description}</Text>
                </View>
              ))
        }

);

在此处输入图像描述

标签: react-nativereact-hooksjsxreact-state

解决方案


我认为您需要将 todos 数组存储在一个反应​​钩子中,这样您对它所做的更改就会立即生效,您可以在父组件中拥有这个 changeTodo 函数并将其作为道具传递,以便从子组件调用它需要的索引。我认为这可能会有所帮助:

export const TeacherMessages = (props) => {
  const [todosArr, setTodosArr] = React.useState(props.todos)

  const checkTodo = (todoIndex) =>{
        let arr = [...todosArr]
        arr[todoIndex].isChecked= true
        setTodosArr(arr)
 }

  return (
    <View
        style={[
        styles.borderBox,
        todosArr.length > 0 || props.notes.length > 0
            ? styles.whiteBox
            : null,
        ]}
    >
        {
            todosArr.map((todo, index) => (
                <View key={todo.id} style={styles.listNotes}>
                  <AntDesign
                      style={styles.listIcon}
                      onPress={() => checkTodo(index)}
                      name={todo.isChecked ? "checksquare" : "exclamationcircle"}
                      color={todo.isChecked ? "green" : "red"}
                      size={18}
                  />
                  <Text style={styles.listText}> {todo.description}</Text>
                </View>
              ))
        }

);

推荐阅读