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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…