今天写页面(react 项目),要实现一个输入框,然后带清除按钮。要求,清除后,光标要focus 到input 里面;
我现在用的是 react 17.0.2 的版本,使用的是函数式组件。之前在class组件中,我们可以这样写:
xxx.jsx
constructor(props) {
super(props);
// 通过React.createRef()创建ref,挂载到组件上
this.inputEl = React.createRef();
}
<input ref={inputEl}></input>
复制代码
然后,我们就可以通过 this.inputEl 来获取到这个 input输入框,blablabla~
函数式组件
const inputEl = useRef(null);
<input ref={inputEl} id='inputAmount' value={inputVal} onChange={handleInputChange}/>
复制代码
然后,通过 inputEl 就可以拿到这个input 输入框了
inputEl.focus() // 获取焦点即可
复制代码
或者,不使用 react 的api 直接使用原生获取节点的办法,例如:
document.querySelector('#inputAmount'); //也可
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END