输入值数组上的useState消除焦点

时间:2019-06-24 14:58:16

标签: react-hooks

我正在使用useState挂钩来更新数组。该数组呈现输入列表。

此代码确实正确更新了useState钩子,但是每次按键后它都会从输入中移出焦点。为什么会发生这种情况,我该如何解决?

import React, { useState } from "react";

const Todos = () => {
    const [todos, setTodos] = useState(["Read book", "Tidy room"]);

    function update(index: number, event: React.ChangeEvent<HTMLInputElement>) {
        const newTodos = [...todos];
        newTodos[index] = event.target.value;
        setTodos(newTodos);
    }

    return (
        <ul>
            {todos.map((item, index) => {
                return (
                    <li key={item}>
                        <input
                            type="text"
                            value={item}
                            onChange={event => update(index, event)}
                        />
                    </li>
                );
            })}
        </ul>
    );
};

export default Exercises;

1 个答案:

答案 0 :(得分:2)

因此,问题在于,您将每个key的项目值用作<li>。当您更改输入中的值时,该键将发生变化并做出反应,从而呈现出一个全新的<li>,而不仅仅是更改屏幕上已经加载的那个。

最简单的解决方案是使每个Todo成为一个对象,并为其赋予不变的id

import React, { useState } from "react";

interface Todo {
  value: string;
  id: string;
}

const Todos = () => {
    const [todos, setTodos] = useState<Todo[]>([
      { 
        value: "Read book",
        id: '1'
      }, 
      {
        value: "Tidy room",
        id: '2'
      }
    ]);

    function update(index: number, event: React.ChangeEvent<HTMLInputElement>) {
        const newTodos = [...todos];
        newTodos[index].value = event.target.value;
        setTodos(newTodos);
    }

    return (
        <ul>
            {todos.map((item, index) => {
                return (
                    <li key={item.id}>
                        <input
                            type="text"
                            value={item.value}
                            onChange={event => update(index, event)}
                        />
                    </li>
                );
            })}
        </ul>
    );
};

export default Exercises;