react/ref-click-counter-func.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>ref click counter</title>
<script src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.14.7/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
function Main() {
console.log('Main')
const counterElem = React.useRef(null)
return (
<div>
<button onClick={() => {
console.log('onClick')
const elem = counterElem.current
elem.innerHTML = (parseInt(elem.innerHTML) + 1).toString()
}}>
Click me
</button>
<div
ref={
(elem) => {
counterElem.current = elem
}
}
>
0
</div>
</div>
)
}
ReactDOM.render( <Main/>, document.getElementById('root'))
</script>
</body>
</html>