繁体   English   中英

从 React 列表中编辑待办事项

[英]Edit todo from list in React

我不知道为什么我不能让它工作,但我只想从列表中编辑待办事项并将其保存在onBlur上(当我在框外按下时)。 我以前做过这项工作,但我想我得了大脑冻结之类的。 我删除了我的尝试,所以现在这些功能是空的。 有人可以将我推向正确的方向或只是填补空白吗? 谢谢

更新:所以我想按下我添加到列表中的待办事项(文本输入),然后编辑已经存在的待办事项,然后再次将其保存到列表中!

      const TEST = () => {
    
        const [todo, setTodo] = useState("")
        const [todoList, setTodoList] = useState([])
      
    
       const onChangeHandler = (text) =>{
            setTodo(text)
        }
    
        const saveTodo = () =>{
            setTodoList([...todoList , {title: todo, key:`${Math.random()}`}])
            setTodo("")
        }
    
    
       const onChangeTodo = () =>{
    
    //UPDATE HERE
       }
    
        const saveonChangeTodo = () =>{
    //SAVE HERE
    
        }
    
        return(
            <View style={{flex:1, backgroundColor: "beige", justifyContent: "center", alignItems: "center", paddingTop: 300,}}>
                <TextInput
                placeholder="Write todo here"
                style={{backgroundColor:"white", padding: 20, width: 300,}}
                value={todo}
                onChangeText={text=>onChangeHandler(text)}
                onBlur={saveTodo}
                />
    
                <FlatList
                data={todoList}
                renderItem={({item}) => {
                    return(<TextInput style={{borderColor: "black", borderWidth: 2, width: 200, padding: 20, margin: 10}}
                    value={item.title}
                    onChangeText={text=>onChangeTodo(text, item)}
                    onBlur={saveonChangeTodo}
                    /> 
                            
                               
                    )
                }}/>

如下更改您的onChangeTodo 不需要saveonChangeTodo因为它已经被onChangeTodo支持。

const onChangeTodo = (text, item) => {
    setTodoList((todos) =>
      todos.map((todo) =>
        todo.key === item.key ? { ...todo, title: text } : todo
      )
    );
};

代码沙箱

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM