如何在 react.js 中将焦点设置在输入字段上?

How to set focus on inputfield in react.js?

如何将焦点设置在最后添加的输入字段上?

我在 www 上找到了几个例子,但都是 class-component,而不是 hook。

我确实尝试过 useref,但我无法让它工作。

import React, { useState } from 'react';

const About = () => {
    const [list, setList] = useState([
        { id: 1, txt: 'text 1' },
        { id: 2, txt: 'text 2' }
    ]);

    return (
        <div className="about">
            <h2>About</h2>

            {list.map((elm) => (
                <input key={elm.id} type="text" defaultValue={elm.txt} />
            ))}

            <button value="ADD" onClick={e => {
                e.preventDefault();
                setList(oldList => ([
                    ...oldList, { id: 3, txt: 'text 3', active: true }
                ]));
            }}>ADD</button>

        </div >
    )
}

export default About;

回调似乎可以做到。

import React, { useState, useCallback } from 'react';

const About = () => {
    const [list, setList] = useState([
        { id: 1, txt: 'text 1' },
        { id: 2, txt: 'text 2' }
    ]);

    const callbackRef = useCallback(inputElement => {
        if (inputElement) {
            inputElement.focus();
        }
    }, []);

    return (
        <div className="about">
            <h2>About</h2>

            {list.map((elm) => (
                elm.active ? <input key={elm.id} type="text" defaultValue={elm.txt} ref={callbackRef} />
                    : <input key={elm.id} type="text" defaultValue={elm.txt} />
            ))}

            <button value="ADD" onClick={e => {
                e.preventDefault();
                setList(oldList => ([
                    ...oldList, { id: 3, txt: 'text 3', active: true }
                ]));
            }}>ADD</button>

        </div >
    )
}

export default About;