微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在输入中打字时失去焦点

如何解决在输入中打字时失去焦点

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

这个错误是在我添加了一些 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",{ name: "Study",]);

  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.3);
    Box-shadow: 30px 30px 20px rgba(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;

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

非常感谢您的帮助!

解决方法

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

TLDR 将所有 const Styled 移到 App 之外

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。