簡體   English   中英

在輸入元素上鍵入時,我的狀態未更新

[英]My state is not updating when typing on the input element

當我嘗試輸入輸入元素時,狀態不會更新。 所以我無法在輸入中輸入任何內容。 我也沒有收到錯誤代碼。 在 handleChange 函數中,當我將它記錄到控制台時,文本變量是未定義的。 但是 value 變量會更新我輸入的每個字母。 但不是作為一個完整的句子,這些字母只是覆蓋了它們自己。

import React, { useState } from "react";

function AddTodo(props) {
  const initialFromState = { text: "", isComplete: null, id: null };
  const [todo, setTodo] = useState(initialFromState);

  const handleSubmit = e => {
    e.preventDefault();
    if (!todo.text) return;
    props.AddTodo(todo);
    setTodo(initialFromState);
    console.log(todo);
  };

  const handleChange = event => {
    const { text, value } = event.target;
    setTodo({ ...todo, [text]: value });
  };

  return (
    <div className="container mx-auto text-center">
      <form onSubmit={handleSubmit} className="rounded flex">
        <input
          className="shadow appearance-none border rounded w-full py-2 mr-4 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
          type="text"
          name="text"
          value={todo.text}
          onChange={handleChange}
          autoComplete="off"
          autoFocus={true}
          placeholder="Eg. Buy apples"
        />
        <button
          type="submit"
          className="bg-blue-500 hover:bg-blue-700 text-white font-bold px-4 rounded focus:outline-none focus:shadow-outline"
        >
          Add
        </button>
      </form>
    </div>
  );
}

export default AddTodo;

我希望我在輸入中輸入的內容存儲在狀態中,並且我可以看到我正在輸入的內容。 下一個挑戰是查看待辦事項是否實際存儲並顯示在其他待辦事項中。 :) 一步到位。

我認為您的handleChange有錯誤的道具名稱, text應該是name

 const handleChange = event => {
    const { name, value } = event.target;
    setTodo({ ...todo, [name]: value });
  };

它應該是name ,你沒有 text 屬性來定位它。

給定的name='text'屬性使用它。

    const { name, value } = event.target;
    setTodo({ ...todo, [name]: value });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM