React_Hooks_Ref
在 Hooks 中想获取到节点
当获取到的节点在方法内 而不是子组件的时候
import React, { useState, useRef, useEffect } from 'react'
import SecondComponent from './Second'
function App() {
const [count, setcount] = useState(0)
const countRef = useRef()
function handleClick() {
setcount(() => {
return count + 1
})
}
useEffect(() => {
console.log(countRef)
console.log(countRef.current)
})
return (
<div>
<span>{count}</span>
<button onClick={handleClick} ref={countRef}>
点击
</button>
<SecondComponent count={count}></SecondComponent>
</div>
)
}
export default App
但是想要获取到子组件的 ref ,那子组件必须是类的形式 否则会报错误,获取不到值
import React, { Component } from 'react'
class SecondComponent extends Component {
constructor(props) {
super(props)
this.state = {
message: '子组件',
}
}
render() {
return (
<div>
{this.props.count} --{this.state.message}
</div>
)
}
}
export default SecondComponent
import React, { useState, useRef, useEffect } from 'react'
import SecondComponent from './Second'
function App() {
const [count, setcount] = useState(0)
const countRef = useRef()
function handleClick() {
setcount(() => {
return count + 1
})
}
useEffect(() => {
console.log(countRef)
console.log(countRef.current)
})
return (
<div>
<span>{count}</span>
<button onClick={handleClick}>点击</button>
<SecondComponent count={count} ref={countRef}></SecondComponent>
</div>
)
}
export default App
Ref 有的时候也可以用于保存上次状态的值
function useCounter() {
const [count, setCoount] = useState(0)
const [updater, setUpdater] = useState(0)
const prevCountRef = useRef()
useEffect(() => {
prevCountRef.current = count
})
const prevCount = prevCountRef.current
return (
<h1>
Now:{count},Before:{prevCount}
</h1>
)
}