简体   繁体   中英

ReactJS - Make Click Event fire before onBlur

I am implementing a custom input element similar to React Select. Users will be able to type something into the input element and select a suggestion from a dropdown (in my case, I implemented a component called SuggestionList which serves the same purpose as that dropdown suggestion list).

Currently, the SuggestionList is a sibling React component to the input element that the user types into (I named it CustomInput).

I want SuggestionList to disappear when CustomInput loses focus, so I implemented an onBlur handler which makes SuggestionList either un-mount or have "display" CSS property set to none. However, the problem is that after SuggestionList disappears, its onClick/handleClick event handler doesn't get called, and that event handler is responsible for adding user-selected elements to the selected items list.

Code shown below. There is more explaination after this code.

const AutocompleteInput = ({...}) => {
    const [suggestionVisible, setSuggestionVisible] = useState(true);

    return (
    ....
    <SystemComponent position="relative">
        <SuggestionList p={theme.space[4]} 
            position="absolute" 
            visible={suggestionVisible}
            value={value} 
            handleClick={handleSelect}
            ref={suggestionBox}
        />
        <CustomInput 
            variant="text" 
            placeholder={placeholder}
            value={value}
            onChange={(evt) => handleInputChange(evt.target.value)}
            onKeyDown={handleKeyDown}
            onFocus={ () => {setSuggestionVisible(true)} }
            onBlur={ () => {setSuggestionVisible(false);} }
        />
    </SystemComponent>
    ....
    )

}

Therefore, when a user clicks something on the SuggestionList, my CustomInput immediately loses focus, causing SuggestionList to either be unmounted/disappear, and thus its event handler isn't called. As a result, the item the user selects isn't added to the suggestion list.

Having that said, I still want SuggestionList to disappear when the user clicks some other part of the website, thereby causing CustomInput to lose focus. Any suggestions?

Let's say you are calling onClickHandler() inside your onClick . You can call this inside the onBlur on function.

For example

onBlur={ () => {onClickHandler(); setSuggestionVisible(false);} }

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