上节课我们介绍了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)就可以实现了,我们来看一下效果:

image-20220120164856391

总结

  • 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/