要使其工作,您需要添加一个新的编辑处理程序,类似于
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}
/>
你不需要绑定函数组件的函数,但是你需要为在
map()
中渲染的每个组件提供一个
key
属性。我已经改变了它,并提供了一个
todoKey
属性,我后来在
<TodoItem />
中使用。
在
<TodoItem />
中,你可以像在
<AddTodo />
中创建新的todo时一样使用类似的逻辑来修改todo文本。当
isEditing
为
true
时,我使用
条件渲染来渲染
<TextInput />
,当它不是这样时则使用
<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
的初始值
- 从
handleEdit
中删除 setText("")
- 它不再需要
const TodoItem = props => {
const [text, setText] = useState(props.title);
const [isEditing, setEdit] = useState(false);
const handleEdit = () => {
props.editHandler(props.todoKey, text);
setEdit(false);
};
return (
{}
)
}