简体   繁体   中英

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.

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. (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(); 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.

The only hack I found so far is wrapping contents of my onBlur in a setTimeout() with an arbitrary timeout duration. 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).

Replace your onClick handlers with onMouseDown . They fire before the blur event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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