上节课我们介绍了effect hook
的使用,接下来我们来介绍组件三大属性中的最后一个,ref hook
回顾
在开始这节课的内容之前,我们来对上节课的内容来做一个简单的回顾
effect hook
是为了使函数式组件使用生命周期钩子useEffect
第二个参数传空数组来标识谁也不监测useEffect
第一个参数是个函数,该函数返回的函数相当于componentWillUnmount
以上便是上节课的内容,接下来我们来介绍一下ref hook
ref hook
我们来新增一个需求:我们要一个输入框,输入数据之后点击按钮,然后弹窗提醒数据:
import React from 'react'; import ReactDOM from 'react-dom'; export default function Demo() { const [ state, setState ] = React.useState({ sum: 0 }); const ref = React.useRef(); React.useEffect(...) function add() {...} function unmount(){...} function show() {alert(ref.current.value);} return ( <div> <h2>sum is : {state.sum}</h2> <input ref={ref} type="text" /> <button onClick={add}>click</button> <button onClick={unmount}>unmount</button> <button onClick={show}>show</button> </div> ); }
我们来看代码,其实ref hook
是最简单的,几乎不需要怎么讲,我们先是定义一个ref
这个ref
是用React.useRef
来生成的,然后把这个ref
绑定给input
标签的ref
属性就好了,然后加一个按钮,绑定onClick
事件,在回调里面alert(ref.current.value)
就可以实现了,我们来看一下效果:
总结
- 用
ref hook
可以是函数式组件使用ref
- 用
useRef
来创建ref
Copyright statement:The articles of this site are all original if there is no special explanation, indicate the source please when you reprint.
Link of this article:https://work.lynchow.com/article/extend_ref_hook/