今天写页面(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






















![[桜井宁宁]COS和泉纱雾超可爱写真福利集-一一网](https://www.proyy.com/skycj/data/images/2020-12-13/4d3cf227a85d7e79f5d6b4efb6bde3e8.jpg)

![[桜井宁宁] 爆乳奶牛少女cos写真-一一网](https://www.proyy.com/skycj/data/images/2020-12-13/d40483e126fcf567894e89c65eaca655.jpg)