Make focus and blur input with react hooks

不羁的心 提交于 2020-12-08 05:08:51

问题


I want to show input results when I focused on this input and hide this result when I blur. I 'v used this code but not work with blur

useEffect(() => {
    if (inputElMovie.current.focus) {
       console.log("meme")
    }     

  }, [movies,inputElMovie]);


回答1:


You don't need useEffect for this case. Create a custom hook with useState(), and return a boolean (show), and an object of event handlers you can spread on the input:

const { useState, useMemo } = React

const usToggleOnFocus = (initialState = false) => {
  const [show, toggle] = useState(initialState);
  
  const eventHandlers = useMemo(() => ({
    onFocus: () => toggle(true),
    onBlur: () => toggle(false),
  }), []);

  return [show, eventHandlers];
}

const Demo = () => {
  const [show, eventHandlers] = usToggleOnFocus();

  return (
    <div>
      <input {...eventHandlers} />
      {show && <div>Content</div>}
    </div>
  );
};

ReactDOM.render(
  <Demo />,
  demo
);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>


<div id="demo"></demo>



回答2:


You need to bind methods to the input JSX tag, like this:

<input
    onFocusOut={() => { /*on removing focus, this can happen when you click on other element in DOM and this one loses focus*/ }}
    onBlur={() => {/*on leaving*/ }}
    onFocus={() => { /*focused*/ }}

></input>

You may not see the option of onFocusOut when coding, but it works.



来源:https://stackoverflow.com/questions/60777063/make-focus-and-blur-input-with-react-hooks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!