简体   繁体   中英

How to show/hide buttons onFocus/onBlur below the textarea and allow to click it?

I need to add two buttons below the input field.

One button will allow saving the input in the textarea, and another aborting.

The buttons should be displayed when the input is focused.

Currently, the problem is that when I click any of the buttons, the input gets blurred again and thus they disappear and the onClick event doesn't happen.

I use MUI and Formik.

Can anyone tell me how to fix it?

 const [buttonClicked, setButtonClicked] = useState(false);... return (... <Box sx={inspectionWrapperStyles} mb={'0.25rem'}> <MultiLineInput name={fieldName} noMargin required={required} label={label} onFocus={() => setInputFocused(true)} onBlur={() => setInputFocused(false)} ref={inputRef} /> {inputFocused && ( <> <IconButton altText="" onClick={() => { console.log('Saved'); }} > <SaveIcon /> </IconButton> <IconButton altText="" onClick={() => { console.log('Aborted'); }} > <XCircleIcon /> </IconButton> </> )} </Box>... )

Looks like currently as you click a button the focus of the input is lost, so they disappear. Maybe it's a good idea to check if the button is clicked and only then hide it, like this:

{inputFocused && !buttonClicked (

then in both button's onClick you can add:

onClick={() => {
  console.log('Aborted');
  setButtonClicked(true);
}}

only thing left is to make sure that we reset it when input is focused again:

onFocus={() => {
  setInputFocused(true);
  setButtonClicked(false);
}}
const [showButton, setShowButton] = useState(false); // add this

<MultiLineInput
         name={fieldName}
         noMargin
         required={required}
         label={label}
         onFocus={() =>{
          setInputFocused(true)
          setShowButton(true) // add this
           }}

         onBlur={() => setInputFocused(false)}
         ref={inputRef}
       />
       {inputFocused && showButton && (
         <>
           <IconButton
             altText=""
             onClick={() => {
               console.log('Saved');
               setShowButton(false) // add this if you want to hide buttons
             }}
           >
             <SaveIcon />
           </IconButton>
           <IconButton
             altText=""
             onClick={() => {
              console.log('Aborted');
              setShowButton(false) // add this if you want to hide buttons
             }}
           >
             <XCircleIcon />
           </IconButton>
         </>
       )}

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