i have input and i want to always keep it onFocused, even i blur it and click on another parts of page, still stay focused.
first i use this
const inputReference = useRef();
const[foc,setFoc] = useState();
const focu =() =>{
const focuss = inputReference.current.onfocus
setFoc(focuss)
}
returrn(
<input ref={inputReference} />
//or
<input type="text" ref={input => input && input.focus()}/>
//or
<input onBlur="focus()" autofocus />
//or
<input onBlur={focu} />
//or
<input type='text' autoFocus={true} onBlur={({ target }) => target.focus()}/>
)
none of them worked
CodePudding user response:
Here's the simple implementation, basically you add event listeners to [mouse-move|click|other] to your parent element
function App () {
const inputRef = React.createRef()
function handleFocus () {
inputRef.current.focus()
}
return (
<div onClick={handleFocus} onm ouseMove={handleFocus}>
<h4>Mouse move or click will focus input inside this gray block</h4>
<input placeholder="text" ref={inputRef} />
</div>
)
}
ReactDOM.render(<App />, document.body);
.container {
background: #eee;
width: 400px;
height: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
CodePudding user response:
You can just focus your input when the component is mounted, and then add an onBlur function on your input
const focus = () => {
inputRef.current.focus()
}
useEffect(() => {
focus()
}, [])
And then for the input
<input ref={inputRef} onBlur={focus} />