作用:获取react中元素的dom对象
步骤:1.导入useRef函数(import {useRef} from 'react')
2.调用useRef函数创建ref对象(const h1=useRef(null))
3.在元素身上通过ref={ref对象}绑定(<h1 ref={h1}>useRef</h1>)
4.通过ref对象.current获取(h1.current.style.color='pink')
小案例:(修改h1字体颜色,并添加边框)
import {useRef} from 'react'
function useRefEg(){
/**
* useRef函数
* 作用:获取react中元素的dom对象
* 步骤:
* 1.导入useRef函数
* 2.调用useRef函数创建ref对象
* 3.在元素身上通过ref={ref对象}绑定
* 4.通过ref对象.current获取
*/
const h1=useRef(null)
// 修改h1字体颜色
const modColor=()=>{
console.log('修改',h1,h1.current);
h1.current.style.color='pink'
h1.current.style.border="2px solid orange"
}
return(
<div>
<h1 ref={h1}>useRef</h1>
<button onClick={modColor}>改变字体颜色</button>
</div>
)
}
export default useRefEg
本文介绍了如何在React应用中利用useRef Hook获取元素的DOM对象,并详细展示了修改元素字体颜色和添加边框的步骤。通过创建ref对象,将其绑定到元素上,然后通过ref.current访问并修改元素样式。
346

被折叠的 条评论
为什么被折叠?



