简体   繁体   English

如何在 onBlur 发生之前运行 onClick?

[英]How to run onClick before onBlur takes place?

I have this tricky problem:我有这个棘手的问题:

I have a text input field and a ul tag with a list of suggestions which when pressed should populate that input field.我有一个文本输入字段和一个带有建议列表的ul 标记,按下这些建议列表时应该填充该输入字段。

export default function SimpleDemo() {
    const [show, setShow] = useState(false)
    const [text, setText] = useState("")

    const updateText = (new_text) => {
        setText(new_text)
        setShow(false)
    }

    return (
        <>
            <input
                type="text"
                value={text}
                onChange={(e) => { setText(e.target.value) }}
                onClick={() => { setShow(true) }}
                onBlur={() => { setShow(false) }} // because of this my updateText() handler never runs
            />
            {show && (
                <ul>
                    <li onClick={() => { updateText("Some Text") }}>Some Text</li>
                    <li onClick={() => { updateText("Suggestion 2") }}>Suggestion 2</li>
                    <li onClick={() => { updateText("Hello World") }}>Hello World</li>
                </ul>
            )}
        </>
    )
}

It works as expected until I add onBlur handler to my input field.在我将onBlur处理程序添加到我的输入字段之前,它会按预期工作。 (because I don't need to show suggestions when I'm not in that field) (因为我不在那个领域时不需要显示建议)

When I add onBlur to my text input, my li tag onClick handler updateText();当我将 onBlur 添加到我的文本输入时,我的li 标签onClick handler updateText(); never runs, thus never populating my input.从不运行,因此从不填充我的输入。 They don't run because my ul tag gets deleted first thus there are no li tag elements with onClick handlers that could be clicked.它们没有运行,因为我的ul 标记首先被删除,因此没有可以单击的带有 onClick 处理程序的li 标记元素。

The only hack I found so far is wrapping contents of my onBlur in a setTimeout() with an arbitrary timeout duration.到目前为止,我发现的唯一 hack 是将我的 onBlur 的内容包装在具有任意超时持续时间的 setTimeout() 中。 But it proved to be unreliable with a small timeout, and a high timeout makes it seem laggy on the front end.但事实证明它在小超时时是不可靠的,而高超时使它在前端看起来很滞后。

Whats a reliable solution?有什么可靠的解决方案?

I'm trying to clone HTML datalist tag functuanality (because it lets me style it).我正在尝试克隆 HTML 数据列表标签功能(因为它可以让我设置样式)。

Replace your onClick handlers with onMouseDown .onMouseDown替换您的onClick处理程序。 They fire before the blur event.它们在模糊事件之前触发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM