当前位置: 首页 > article >正文

【React】自定义hook函数

1. 概念

本质:函数
在这里插入图片描述

2. 例子

  • 需求:实现点击按钮的展示与隐藏子组件
2.1 不封装直接实现
import { useState } from 'react'
function Son() {
  return <div>子组件</div>
}

function App() {
  const [isShow, setIsShow] = useState(true)
  function toggle() {
    setIsShow(!isShow)
  }
  return (
    <div className="App">
      {isShow && <Son />}
      <button onClick={toggle}>点击我,隐藏子组件</button>
    </div>
  );
}

export default App;

2.2 封装自定义hook实现
import { useState } from 'react'
function Son() {
  return <div>子组件</div>
}

function useToggle() {
  const [isShow, setIsShow] = useState(true)
  function toggle() {
    setIsShow(!isShow)
  }
  return {
    isShow,
    toggle
  }
}

function App() {
  const { isShow, toggle } = useToggle()
  return (
    <div className="App">
      {isShow && <Son />}
      <button onClick={toggle}>点击我,隐藏子组件</button>
    </div>
  );
}

export default App;

3 总结(封装自定义hook通用思路)

  1. 声明一个use开头的函数
  2. 在函数体内封装可复用的逻辑
  3. 把组件中用到的状态或者回调return出去(以对象或者数组的形式)
  4. 在哪个组件中要用到这个逻辑,就执行这个函数,解构出状态和回调进行使用
4 参考

黑马程序员react教程


http://www.kler.cn/news/330791.html

相关文章:

  • String的内存分配与拼接操作
  • (done) Go 语言:三种多文件协作方式
  • Web安全 - 文件上传漏洞(File Upload Vulnerability)
  • input.file.value无法使用
  • 助力企业信息化,开源免费工作流引擎AntFlow推出重榜功能tidb支持,为工作流引擎水平扩展提供无限可能
  • 【算法与图】通向高效解决方案的钥匙
  • 【三步 完全离线搭建 openwebui 】
  • py-mmcif包pdbx_struct_oper_list对象介绍
  • Redis篇(Redis原理 - RESP协议)
  • 华硕天选笔记本外接音箱没有声音
  • 【Verilog学习日常】—牛客网刷题—Verilog企业真题—VL74
  • 小徐影院:Spring Boot影院管理新体验
  • Web3 游戏周报(9.22 - 9.28)
  • 2023_Spark_实验十:Centos_Spark Local模式部署
  • Python知识点:如何使用Raspberry Pi与Python进行边缘计算
  • 【Python实战】制作空气质量评估系统
  • Java后端微服务架构下的配置动态刷新:Spring Cloud Bus
  • 华为eNSP:MAC地址安全
  • 机器学习周报(9.23-9.29)
  • Python多个set中的交集