问题
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