react项目,函数式组件如何使用useref()创建ref引用?
发布于 作者:苏南大叔 来源:程序如此灵动~
react
项目的使用方式有类式组件和函数式组件,两者使用ref
引用的姿势是完全不同的。在上一篇文章中,已经探讨了在类式组件中使用createRef()
创建引用的方式,本文探讨的是在函数式组件中使用useRef()
来实现同样的需求。
大家好,这里是苏南大叔的程序如此灵动博客,这里记录苏南大叔和计算机代码的故事。本文中将以react
函数式组件的视角,重新审视ref
的使用方式。如何创建一个引用,如何使用这个引用。当然,引用的对象仍然是以input
为例,来说明一下最常见的使用方式。测试环境:create-react-app@5.0.1
,react@18.2.0
,react-dom@18.2.0
,node@16.14.2
。
前文回顾
有关类式react
组件中,使用ref
的方式,请参考文章:
关键代码就是:
this.inputRef = React.createRef();
<input type="text" ref={this.inputRef} />
this.inputRef.current.value
那么,在函数式组件里面,又如何编写上面的这三个关键性代码呢?
函数式组件,创建并绑定ref
引用
import { useRef } from "react";
function Child() {
const inputRef = useRef(null)
return (
<div className="Child">
<input type="text" ref={inputRef} defaultValue="" />
</div>
);
}
export default Child;
useRef()
和createRef()
有所不同的是:
createRef()
定义在react
对象上。useRef()
是单独导入的。
其它的看起来一样,都可以设置默认初始值null
。不过对于绑定在input
这样的dom
上的话,初始值也没有特别大的用途。这个,待后续讨论。
函数式组件,使用ref
的current
import { useRef } from "react";
function Child() {
const inputRef = useRef(null)
const test = () => {
if (inputRef.current) {
console.log(inputRef.current.value);
}
}
return (
<div className="Child">
<input type="text" ref={inputRef} defaultValue="" onChange={test.bind()} />
</div>
);
}
export default Child;
关键代码还是:
if (inputRef.current) {
console.log(inputRef.current.value);
}
和类式组件的相关关键代码对比,就是少了一个this.
。
实例代码
再加上一个输入框的主动聚焦功能代码,最终的范例代码如下:
import { useRef } from "react";
function Child() {
const inputRef = useRef(null)
const handleFocus = () => {
inputRef.current.focus()
}
const test = () => {
if (inputRef.current) {
console.log(inputRef.current.value);
}
}
return (
<div className="Child">
<input type="text" ref={inputRef} onChange={test.bind()} defaultValue="" />
<button onClick={handleFocus}>Focus the input</button>
</div>
);
}
export default Child;
实现的功能需求是和上一篇类式组件文章的需求是一致的,就是写法不一样而已。这两篇文章里面,都是把ref
绑定到了输入框上,然后通过ref
拿到了输入框的value
,然后还通过ref
对输入框进行了主动聚焦操作。
对于函数式组件中,无需传递参数的事件函数来说,两种写法都是可以的:“直接写函数名”,或者写“函数名.bind()”。具体可以参考下面的文字:
相关链接
- https://newsn.net/say/react-createref.html
- https://newsn.net/say/react-state.html
- https://newsn.net/say/react-memo.html
- https://newsn.net/say/react-bind.html
- https://newsn.net/say/react-pure-component.html
- https://newsn.net/say/create-react-app.html
总结
更多由苏南大叔编写的react
经验文章,请点击下面的链接:


