【问题标题】:How to set focus on inputfield in react.js?如何在 react.js 中设置输入字段的焦点?
【发布时间】:2020-10-11 13:38:34
【问题描述】:

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

我在 www 找到了一些示例,但都是类组件,而不是钩子。

我确实尝试过 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;

【问题讨论】:

    标签: reactjs input focus


    【解决方案1】:

    回调似乎可以做到。

    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-18
      • 2020-11-05
      • 2018-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多