react常用Hooks

Hooks是可从函数组件"挂钩"到React状态和生命周期功能的函数。 Hooks在class中是无效的------可在没有class的情况下使用React。(不推荐重写已有组件,但是如果愿意,可以在一些新的组件中使用 Hooks。)React提供一些内置的 Hooks,比如useState。用户也可以创建自己的 Hooks,以在不同组件之间重复使用有状态的行为。(来源于 React文档的描述)

1. react-fetch-hook

react-fetch-hook 是用于便捷使用Fetch API的React Hooks。这个程序包包括以下内容:

· Tiny(397B) --- 按大小限制计算

· 包括 Flow 和 TypeScript 类型

react-fetch-hook

准备开始

javascript 复制代码
Yarn

yarn add react-fetch-hook

NPM

npm i react-fetch-hook --save

使用

import React from "react";

import useFetch from "react-fetch-hook";

const Component = () => {

const { isLoading, data } =useFetch("https://swapi.co/api/people/1");

return isLoading ? (

<div>Loading...</div>

) : (

<UserProfile {...data} />

);

};

useFetch 接收与fetch函数同样的参数。

自定义格式化程序

默认格式化程序是 response => response.json() 。可以这样传递自定义格式化程序:

const { isLoading, data } =useFetch("https://swapi.co/api/people/1", {

formatter: (response) =>response.text()

});

多个请求

支持在同一文件/组件里的多个useFetch示例:

const result1 = useFetch("https://swapi.co/api/people/1");

const result2 = useFetch("https://swapi.co/api/people/2");if(result1.isLoading && result2.isLoading) {

return<div>Loading...</div>;

} return <div>

<UserProfile {...result1.data}/>

<UserProfile {...result2.data}/>

</div>
  1. @rehooks/window-scroll-position

@rehooks/window-scroll-position是用于决定窗口-滚动位置的ReactHooks。当用户根据滚动动作对对象进行动画处理时,Hooks用处颇大。

@rehooks/window-scroll-position

安装

yarn add@rehooks/window-scroll-position

使用

javascript 复制代码
Yarn

yarn add react-fetch-hook

NPM

npm i react-fetch-hook --save

使用

import React from "react";

import useFetch from "react-fetch-hook";

const Component = () => {

const { isLoading, data } =useFetch("https://swapi.co/api/people/1");

return isLoading ? (

<div>Loading...</div>

) : (

<UserProfile {...data} />

);

};

useFetch 接收与fetch函数同样的参数。

自定义格式化程序

默认格式化程序是 response => response.json() 。可以这样传递自定义格式化程序:

const { isLoading, data } =useFetch("https://swapi.co/api/people/1", {

formatter: (response) =>response.text()

});

多个请求

支持在同一文件/组件里的多个useFetch示例:

const result1 = useFetch("https://swapi.co/api/people/1");

const result2 = useFetch("https://swapi.co/api/people/2");if(result1.isLoading && result2.isLoading) {

return<div>Loading...</div>;

} return <div>

<UserProfile {...result1.data}/>

<UserProfile {...result2.data}/>

</div>
  1. @rehooks/local-storage

@rehooks/local-storage 是负责同步本地存储的React Hooks。

@rehooks/local-storage

安装

Yarn

yarn add @rehooks/local-storage

NPM

npm i @rehooks/local-storage

使用

javascript 复制代码
writeStorage:可以在应用程序中任何地方。

import React from 'react';

import { writeStorage } from '@rehooks/local-storage';let counter = 0;constMyButton = () => (

<button onClick={_ =>writeStorage('i', ++counter)}>

Click Me

</button>

);

useLocalStorage:该组件将从本地储存中接收更新。

import React from 'react';

import { useLocalStorage } from '@rehooks/local-storage';function MyComponent(){

const [counterValue] =useLocalStorage('i'); // send the key to be tracked.

return (

<div>

<h1>{counterValue}</h1>

</div>

);

}

deleteFromStorage: 也可以从本地储存中删除项目。

import { writeStorage,deleteFromStorage } from '@rehooks/local-storage';writeStorage('name', 'HomerSimpson'); // Add an item firstdeleteFromStorage('name'); // Deletes theitemconst thisIsNull = localStorage.getItem('name'); // This is indeed null

完整示例

import React from 'react';

import ReactDOM from 'react-dom';

import { writeStorage, deleteFromStorage, useLocalStorage } from'@rehooks/local-storage';const startingNum = 0;const App = () => {

const [getNum, setNum] =useLocalStorage('num'); return (

<>

<p>{getNum}</p>

<button onClick={_ =>setNum(getNum ? getNum + 1 : 0)}>Increment</button>

<button onClick={_ =>deleteFromStorage('num')}>Delete</button>

</>

);

};// Assuming there is a div in index.html with an ID of 'root'

ReactDOM.render(<App />, document.getElementById('root'));

@rehooks/local-storage API 文档可以从这里找到。
  1. react-use-form-state

在React中管理表单状态有时候可能有些难以处理。现在已经有很多好的方法轻松解决这一问题。然而,其中的许多方法中包含了大量可能最终都没有用过的特性,并且/或者需要传递一些额外的字节。

幸运的是,最近对React Hooks的引进和编写自定义 Hooks的能力已经为分享状态逻辑提供了新的可能性。表单状态也不例外。

react-use-form-state 是一个小React Hooks,其尝试使用用户熟悉的本地表单输入元素来简化管理表单状态。

react-use-form-state

准备开始

首先,在项目中添加react-use-form-state :

npminstall --save react-use-form-state

请注意, react-use-form-state 需要 react@^16.8.0作为一个对等依赖。

基本用法

import { useFormState } from'react-use-form-state';export default function SignUpForm({ onSubmit }) {

const formState, { text, email,password, radio } = useFormState(); functionhandleSubmit(e) {

// ...

} return (

<form onSubmit={handleSubmit}>

<input {...text('name')} />

<input {...email('email')}required />

<input {...password('password')}required minLength="8" />

<input {...radio('plan','free')} />

<input {...radio('plan','premium')} />

</form>

);

}

由以上例子,当用户填写表单时,formState对象内容如下:

{

values: {

name: 'Mary Poppins',

email: 'mary@example.com',

password: '1234',

plan: 'free',

},

touched: {

name: true,

email: true,

password: true,

plan: true,

},

validity: {

name: true,

email: true,

password: false,

plan: true,

},

errors: {

password: 'Please lengthen this textto 8 characters or more',

},

clear: Function,

clearField: Function,

reset: Function,

resetField: Function,

setField: Function,

}

初始状态

useFormState 需要一个初始状态对象,其键与输入名称匹配。

export default functionRentCarForm() {

const formState, { checkbox, radio,select } = useFormState({

trip: 'roundtrip',

type: 'sedan', 'suv', 'van',

});

return (

<form>

<select {...select('trip')}>

<optionvalue="roundtrip">Same Drop-off</option>

<optionvalue="oneway">Different Drop-off</option>

</select>

<input {...checkbox('type','sedan')} />

<input {...checkbox('type','suv')} />

<input {...checkbox('type','van')} />

<button>Submit</button>

</form>

);

}

  1. @rehooks/component-size

@rehooks/component-size是一个决定组件大小的React Hooks。当调整响应式图片和组件大小需要局部刷新时十分有用。

@rehooks/component-size GitHub page

安装

yarn add @rehooks/component-size

使用

javascript 复制代码
import { useRef } from 'react'

import useComponentSize from '@rehooks/component-size'function MyComponent() {

let ref = useRef(null)

let size = useComponentSize(ref)

// size == { width: 100, height: 200 }

let { width, height } = size

let imgUrl =`https://via.placeholder.com/${width}x${height}` return (

<div style={{ width: '100%',height: '100%' }}>

<img ref={ref} src={imgUrl}/>

</div>

)

}

注意:ResizeObserver是用来决定是否调整元素大小的API(应用程序编程接口)。Chrome的浏览器支持更优越,然而其他主流浏览器却缺乏这一功能。

ResizeObserver browser support

  1. use-onclickoutside

这是一个用于监听元素外部点击的React Hooks。在与模态窗口、弹出窗口、警报或者配置文件导航的结合中,这种 Hooks十分有用。

use-onclickoutside

入门指南

Yarn

yarn add use-onclickoutside

用法

创建一个ref并把它传递给useOnClickOutside Hooks。

javascript 复制代码
import { useRef } from 'react'

import useComponentSize from '@rehooks/component-size'function MyComponent() {

let ref = useRef(null)

let size = useComponentSize(ref)

// size == { width: 100, height: 200 }

let { width, height } = size

let imgUrl =`https://via.placeholder.com/${width}x${height}` return (

<div style={{ width: '100%',height: '100%' }}>

<img ref={ref} src={imgUrl}/>

</div>

)

}

请注意useRef的用法,它是由标准React包提供的标准ReactHooks。

useRef返回一个可变的ref对象,其.current特性被初始化为传递的参数(initialValue)。这个返回的对象将持续存在于整个组件的生命周期。

大家有木有学习到?掌握这些,做一个快乐的程序员吧~

相关推荐
北城笑笑4 小时前
Vue 112 ,下篇:前端 dist 还原成 Vue3 + Vite 项目( krpano 全景接入与页面适配实战,Vue2 → Vue3 )
前端·javascript·vue.js·3d·前端框架·vue·webgl
我叫黑大帅4 小时前
搜“张三”把备注也带出来了?不用加高级筛选,如何让一个搜索框实现「选项直达」!
前端·javascript·面试
如夏倾城6 小时前
WAF (Web Application Firewall,Web应用防火墙)
前端·网络·安全·web安全·web app
图扑可视化7 小时前
基于图扑软件智慧制硅厂 Web SCADA 开发实践
前端·三维可视化·scada·hmi·组态软件
前端fighter7 小时前
2026年前端面试题总结(pdf版)
前端·pdf
谢小飞7 小时前
运维加了个参数,我们的网页挂掉了
前端·浏览器
CoderYanger8 小时前
Java EE 进阶:12.Spring AOP(第二弹)
java·前端·数据库·spring boot·spring·java-ee·mybatis
用户693717500138411 小时前
大模型蒸馏到底在蒸什么?一篇文章搞懂知识蒸馏概念
前端·后端·github
徐小夕11 小时前
实测 10 个前端 UI 生成开源 Skill|AI 输出直达上线标准
前端·vue.js·github
tong_li11 小时前
给娃做个 AI 陪写作业助手:LangChain4j 入门(八):AI 知道这字哪课学的(SQLite 结构化查询入门)
前端·langchain