Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

javascript - 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).

question from:https://stackoverflow.com/questions/65924477/how-to-run-onclick-before-onblur-takes-place

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...