【发布时间】:2021-02-19 01:02:14
【问题描述】:
当我在输入字段中输入内容并按键盘上的 Enter 键时,我想自动将该项目添加到列表中,一旦添加,我也想清除输入字段。我想我应该在按 Enter 时使用 useRef 但不知道该怎么做?
import React, { useState } from "react";
import { v4 as uuidv4 } from "uuid";
const initialList = [
{
id: "a",
name: "Robin",
},
{
id: "b",
name: "Dennis",
},
];
const AppAddItem = () => {
const [list, setList] = useState(initialList);
const [name, setname] = useState("");
const handleChange = (event) => {
setname(event.target.value);
};
const handleAdd = () => {
const newList = list.concat({ name, id: uuidv4() });
setList(newList);
setname("");
};
return (
<div>
<AddItem name={name} onChange={handleChange} onAdd={handleAdd} />
<List list={list} />
</div>
);
};
const AddItem = ({ onChange, name, onAdd }) => {
return (
<div>
<div>
<input type="text" value={name} onChange={onChange} />
<button type="button" onClick={onAdd}>
Add
</button>
</div>
</div>
);
};
const List = ({ list }) => {
return (
<form>
{list.map((item) => {
return <li key={item.id}>{item.name}</li>;
})}
</form>
);
};
export default AppAddItem;
【问题讨论】:
-
您可能希望使用 onKeyDown 而不是 onChange 来处理输入。在这里使用“Enter”键有一个很好的解释:stackoverflow.com/questions/27827234/…