web前端全系列 教程
1839个小节阅读:2243.7k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
useRef(initialValue)
useRef
返回一个可变的 ref 对象
参数为其 .current
属性的初始值
xxxxxxxxxx
import React,{useRef} from 'react';
export default function UseRefTest() {
const inputRef = useRef(null);
//访问inputRef的current属性就可以访问到inputDOM
return (
<div>
<input ref={inputRef}/>
<button onClick={()=>inputRef.current.focus()}>获得焦点</button>
</div>
);
}
提示:
使用useRef可以代替React.createRef()
xxxxxxxxxx
import React, { useState } from 'react'
export default function UseRefTest() {
let count = 0
const [time,setTime]=useState()
const changeCount=()=>{
count++
setTime(new Date().toLocaleTimeString())
}
const showCount = () => {
// 引用调用了changeCount,组件会重新渲染,则组件的代码会重新执行,那么count就一直被重置为0,所以永远拿不到count更改后的值
console.log(count)
}
return (
<div>
<button onClick={changeCount}>更改count</button>
<button onClick={showCount}>查看count</button>
<h3>当前时间是:{time}</h3>
</div>
)
}
xxxxxxxxxx
import React, { useRef, useState } from 'react'
export default function UseRefTest() {
//使用ref保存的数据,即使组件重新渲染,它也不会被重置
const count = useRef(0)
const [time,setTime]=useState()
const changeCount=()=>{
count.current++
setTime(new Date().toLocaleTimeString())
}
const showCount = () => {
console.log(count)
}
return (
<div>
<button onClick={changeCount}>更改count</button>
<button onClick={showCount}>查看count</button>
<h3>当前时间是:{time}</h3>
</div>
)
}
实时效果反馈
1. 使用___Hook来创建Refs:
A useState
B useEffect
C useRef
D useContext
答案
1=>C