- 用以下三种方式创建 Ref 都可以
import React from 'react'
export default function Count () {
const [count ,setCount] = React.useState(0)
const myRef = React.createRef()
const myRef2 = React.useRef() // Ref Hook 的方式
const myRef3 = {current: undefined}
const addNumber = () => {
setCount(count => count + 1)
}
const showCount = () => {
console.log(myRef3.current.innerText)
}
return (
<div>
<h2 ref={myRef3}>当前和为 {count}</h2>
<button onClick={addNumber}>+1</button>
<button onClick={showCount}>显示和</button>
</div>
)
}