gpt4 book ai didi

javascript - 如何在 React Native 中编辑平面列表项

转载 作者:行者123 更新时间:2023-12-01 16:25:01 25 4
gpt4 key购买 nike

我这周刚开始学习 React Native,在看了一些长的 youtube 教程后,我决定创建一个待办事项列表应用程序,人们可以在其中添加、删除和编辑生成的待办事项列表。目前我的代码只能添加和删除,但我想知道如何将编辑功能添加到我的项目中,我不知道如何使它工作,所以如果有人能帮助我解决这个问题,那就太棒了。

这是我的项目的一个codesandbox https://codesandbox.io/s/vigilant-williamson-4zv7s?file=/src/App.js

如果你有任何问题,请在评论中告诉我

最佳答案

要使其正常工作,您需要添加新的编辑处理程序,类似于 pressHandler , 但编辑条目而不是删除它。可能的编辑处理程序可能如下所示:

const editHandler = (todoKey, newText) => {
const newTodos = [...todos];
const index = newTodos.findIndex(todos => todos.key === todoKey);
newTodos[index] = Object.assign(newTodos[index], { value: newText });

setTodos(newTodos);
};

它将编辑的元素移动到列表的末尾。如果需要,您可以自行更改此行为。

然后你需要将处理程序传递给<TodoItem /> :

<TodoItem
key={item.key}
todoKey={item.key}
title={item.value}
editHandler={editHandler}
pressHandler={pressHandler}
/>

不需要绑定(bind)函数组件函数,但是需要提供一个key您在 map() 中渲染的每个组件的 Prop .我已经更改并提供了一个 todoKey我后来在 <TodoItem /> 中使用的 Prop .

<TodoItem />您可以使用与在 <AddTodo /> 中使用的类似逻辑来修改待办事项文本用于创建新的待办事项。我用 conditional rendering渲染 <TextInput />什么时候isEditingtrue , 和 <Text />当它不是。

{isEditing 
? <TextInput value={text} onChangeText={setText} style={styles.itemText} />
: <Text style={styles.itemText}>{props.title}</Text>
}

同样,我有条件地呈现保存编辑按钮。

完整 <TodoItem />组件:

const TodoItem = props => {
const [text, setText] = useState("");
const [isEditing, setEdit] = useState(false);

const handleEdit = () => {
props.editHandler(props.todoKey, text);
setText("");
setEdit(false);
};

return (
<View style={styles.items}>
<View style={styles.itemContainer}>
{isEditing
? <TextInput value={text} onChangeText={setText} style={styles.itemText} />
: <Text style={styles.itemText}>{props.title}</Text>
}
<View style={styles.btnContainer}>
<Buttons title="Delete" onPress={() => props.pressHandler(props.todoKey)} style={styles.itemBtn} />
{isEditing
? <Buttons title="Save" onPress={handleEdit} style={styles.editBtn} />
: <Buttons title="Edit" onPress={() => setEdit(true)} style={styles.editBtn} />
}
</View>
</View>
</View>
);
};

const styles = /* ... */

这是带有代码的codesandbox:https://codesandbox.io/s/public-edit-todo-item-bsc9p


编辑 1

如果您想在编辑期间加载当前的 TODO 标题而不是先清除它,请更改 <TodoItem /> :

  • 设置props.title作为 text 的初始值
  • 删除setText("")来自 handleEdit - 不再需要了
const TodoItem = props => {
const [text, setText] = useState(props.title);
const [isEditing, setEdit] = useState(false);

const handleEdit = () => {
props.editHandler(props.todoKey, text);
setEdit(false);
};

return (
{/* stays the same */}
)
}

关于javascript - 如何在 React Native 中编辑平面列表项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63178260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com