按 Enter 键时在列表中添加项目并清除输入字段

Add item on the list when pressing Enter and clear input field

当我在输入字段中键入内容并按键盘上的 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;

<input> 上有 onKeyDown 活动。我们可以在其中传递我们的函数,并在 event.key 的帮助下可以检查 Enter 是否被按下。如果按下,则只需执行与 handleAdd.

中相同的操作

Working Demo

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 handleKeyDown = (event) => {
    if (event.key === "Enter") {
      handleAdd();
    }
  };

  const handleAdd = () => {
    const newList = list.concat({ name, id: uuidv4() });
    setList(newList);
    setname("");
  };

  return (
    <div>
      <AddItem
        name={name}
        onChange={handleChange}
        onAdd={handleAdd}
        handleKeyDown={handleKeyDown}
      />
      <List list={list} />
    </div>
  );
};

const AddItem = ({ onChange, name, onAdd, handleKeyDown }) => {
  return (
    <div>
      <div>
        <input
          type="text"
          value={name}
          onChange={onChange}
          onKeyDown={handleKeyDown}
        />
        <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;