【发布时间】:2020-08-08 09:19:13
【问题描述】:
所以我有这个待办事项列表应用程序,我正在编辑待办事项的名称。
当我点击按钮 edit 时,我在输入字段中获取名称的值,当我在该字段中输入内容并按 Enter 时,它应该更改/更新待办事项的名称,但现在它是只添加新的待办事项。
这是我目前工作的代码,我删除了所有不成功的尝试。我没有更多的想法了。
import React, { useRef, useReducer } from 'react'
function App() {
const inputRef = useRef<HTMLInputElement | any>(null)
const handleSubmit = (e: any) => {
e.preventDefault()
inputRef.current?.value !== "" && dispatch({ type: 'ADD_TODO', payload: inputRef.current?.value })
inputRef.current && (inputRef.current.value = "")
}
const [todo, dispatch] = useReducer((state: any, action: any): any => {
switch (action.type) {
case 'ADD_TODO':
return [...state, { id: state.length, name: action.payload, isCheck: false }]
case 'CHECK_TODO':
return state.filter((item: any, index: any): any => {
if (index === action.id) {
item.isCheck = !item.isCheck
}
return item
})
case 'DELETE_TODO':
return state.filter((item: any, index: any) => index !== action.id)
case 'EDIT_TODO':
inputRef.current.focus()
inputRef.current.value = action.payload
return state
}
}, [])
const todos = todo.map((item: any, index: number) => {
return (
<li key={index}>
<input type="checkbox" checked={item.isCheck} onChange={() => dispatch({ type: "CHECK_TODO", id: index })} />
{item.name}
<button onClick={() => dispatch({ type: 'EDIT_TODO', id: index, payload: item.name })}>edit</button>
<button onClick={() => dispatch({ type: "DELETE_TODO", id: index })}>x</button>
</li>
)
})
return (
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder='Buy milk'
ref={inputRef}
/>
</form>
<ul>{todos}</ul>
</div>
)
}
export default App
编辑
此外,作为选项,可以添加新按钮来提交编辑,而不是按 Enter。
【问题讨论】:
标签: reactjs