在输入中打字时失去焦点

时间:2021-03-30 17:20:36

标签: reactjs state react-state

我一直试图弄清楚为什么我的文本输入在通过问题输入一个字符后失去焦点,但我没有找到运气。

这个错误是在我添加了一些 CSS 代码之后发生的。

这是代码:

import React, { useState } from "react";
import { v4 as uuidv4 } from "uuid";
import styled from "styled-components";

const App = () => {
  const [input, setInput] = useState("");
  const [todos, setTodos] = useState([
    { name: "Feed the dog", id: uuidv4() },
    { name: "Help mother", id: uuidv4() },
    { name: "Study", id: uuidv4() },
  ]);

  const StyledList = styled.div`
    justify-content: center;
    text-align: center;
    align-items: center;
    max-width: 40%;
    margin: 8rem auto;
    box-shadow: red;
    min-height: 60vh;
    border: 1px solid rgba(0, 0, 0, 0.3);
    box-shadow: 30px 30px 20px rgba(0, 0, 0, 0.3);
  `;

  const StyledButtonList = styled.div`
    display: flex;
    justify-content: center;
  `;

  const StyledTodo = styled.div`
    display: flex;
    flex-direction: column;
    width: 30%;
    margin: auto;
  `;

  const StyledButton = styled.button`
    margin-left: 2%;
  `;

  const StyledP = styled.p`
    display: flex;
    justify-content: space-between;
  `;

  const clearAll = () => {
    if (window.confirm("Do you want to delete all?")) {
      setTodos([]);
    }
  };

  const deleteTask = (id) => {
    setTodos(todos.filter((todo) => todo.id !== id));
    console.log(id);
  };

  return (
    <StyledList>
      <h1>What are the plans for today?</h1>
      <form>
        <input
          type="text"
          placeholder="Add Todo"
          value={input}
          onChange={(e) => setInput(e.target.value)}
        ></input>
        <button
          onClick={(e) => {
            e.preventDefault();
            setTodos([
              ...todos,
              {
                name: input,
                id: uuidv4(),
              },
            ]);
          }}
        >
          Add
        </button>
        <h1>Your todos:</h1>
      </form>
      <StyledTodo>
        {todos.map((todo) => {
          return (
            <StyledP>
              {todo.name}{" "}
              <StyledButtonList>
                <StyledButton onClick={() => deleteTask(todo.id)}>
                  x
                </StyledButton>{" "}
              </StyledButtonList>
            </StyledP>
          );
        })}
      </StyledTodo>
      <button onClick={() => clearAll()}> Remove all </button>
    </StyledList>
  );
};

export default App;

我已尝试按照某些答案的建议在输入中设置一个键,但我仍然找不到解决此问题的方法。

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

使用 styled-components 库,您可能看起来只是添加了一些 CSS,但实际上您声明了几个新的 React 组件。并且您在使用它们的组件中声明了它们。这意味着,这些样式化组件在每次渲染时都会重新声明。每次你输入一个字符,App 的状态都会改变并且 React 会重新渲染它,在渲染过程中它会重新声明 StyledList,当 React 将你之前拥有的组件树与新的组件树进行比较并注意到它是不同的,因为旧的 StyledList 与新的 StyledList 不同,所以 React 从头开始​​创建所有内容,新的 StyledList 和新的输入。并且新输入没有聚焦,因为为什么会这样?

TLDR 将所有 const Styled 移到 App 之外