You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
45 lines
1.0 KiB
45 lines
1.0 KiB
import React, { useEffect, useRef } from 'react'
|
|
|
|
// useRef:在函数组件中获取真实的dom元素对象或者是组件对象
|
|
/**
|
|
* 使用步骤
|
|
* 1. 导入 useRef 函数
|
|
* 2. 执行 useRef 函数并传入null,返回值为一个对象 内部有一个current属性存放拿到的dom对象(类组件实例)
|
|
* 3. 通过ref 绑定 要获取的元素或者组件
|
|
*/
|
|
|
|
class TestC extends React.Component {
|
|
state = {
|
|
name: 'Ken'
|
|
}
|
|
|
|
getName = () => {
|
|
return 'this is child Test'
|
|
}
|
|
|
|
render () {
|
|
return (
|
|
<div>类组件</div>
|
|
)
|
|
}
|
|
}
|
|
|
|
function App () {
|
|
const testRef = useRef(null)
|
|
const h1Ref = useRef(null)
|
|
|
|
// useEffect 回调是在 dom 渲染之后的。和 vue 里的 watch 效果较像,但是执行时机是不同的
|
|
useEffect(() => {
|
|
console.log(testRef.current)
|
|
console.log(h1Ref.current)
|
|
}, [])
|
|
|
|
return (
|
|
<div>
|
|
<TestC ref={testRef}/>
|
|
<h1 ref={h1Ref}>this is h1</h1>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
export default App
|