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常用Hooks_第1张图片

react-fetch-hook

准备开始

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 ? (

Loading...
) : ( ); }; 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
Loading...
; } return

2. @rehooks/window-scroll-position

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

react常用Hooks_第2张图片

@rehooks/window-scroll-position

安装

yarn add@rehooks/window-scroll-position

使用

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 ? (

Loading...
) : ( ); }; 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
Loading...
; } return

3. @rehooks/local-storage

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

react常用Hooks_第3张图片

@rehooks/local-storage

安装

Yarn

yarn add @rehooks/local-storage

NPM

npm i @rehooks/local-storage

使用

writeStorage:可以在应用程序中任何地方。

import React from 'react';

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



);

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

import React from 'react';

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

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

return (

{counterValue}

); } 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 ( <>

{getNum}

); };// Assuming there is a div in index.html with an ID of 'root' ReactDOM.render(, document.getElementById('root')); @rehooks/local-storage API 文档可以从这里找到。

4. react-use-form-state

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

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

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

react常用Hooks_第4张图片

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 (

);

}

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

{

values: {

name: 'Mary Poppins',

email: '[email protected]',

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 (

);

}

5. @rehooks/component-size

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

react常用Hooks_第5张图片

@rehooks/component-size GitHub page

安装

yarn add @rehooks/component-size

使用

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 (

) }

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

react常用Hooks_第6张图片

ResizeObserver browser support

6. use-onclickoutside

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

react常用Hooks_第7张图片

use-onclickoutside

入门指南

Yarn

yarn add use-onclickoutside

用法

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

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 (

) }

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

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

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

react常用Hooks_第8张图片

你可能感兴趣的:(react.js,前端,前端框架)