react Hooks :useRef的使用
程序员文章站
2022-05-29 11:57:37
...
//useRef 作用 获取子组件或者DOM节点的句柄,渲染周期之间共享数据的存储
import React, { useState, useEffect, PureComponent, useMemo, useRef, useCallback } from 'react'
//函数组件获取不了ref
class Counter extends PureComponent {
speak = () => {
console.log('speak', this.props.count)
}
render() {
const { props } = this
return (
<h1 onClick={props.onClick}>{props.count}</h1>
)
}
}
function APP(props) {
const [count, setCount] = useState(0)
const double = useMemo(() => {
return count * 2
}, [count === 3])
const CounterRef = useRef()//使用CounterRef获取Counter这个组件
const onClick = useCallback(() => {
console.log('Click')//
// console.log(CounterRef.current)//CounterRef.current返回就是Counter这个组件
CounterRef.current.speak()//通过Counter组件的speak()
}, [CounterRef])
const it = useRef()
useEffect(() => {
it.current = setInterval(() => {
setCount(count => count + 1)
}, 1000)
//定时器,让count每秒加1
}, [])
useEffect(() => {
if (count >= 10) {
clearInterval(it.current)
//清除定时器
}
})
return (
<div>
<button
type="button"
onClick={() => { setCount(count + 1) }}
>
Click({count}),double:{double}
</button>
<Counter ref={CounterRef} count={count} onClick={onClick} />
</div>
)
}
export default APP
上一篇: React 初学 - props属性 - 个人笔记11
下一篇: react.js动态样式写法