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)。这个返回的对象将持续存在于整个组件的生命周期。

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

相关推荐
Sam90291 分钟前
【Webpack--013】SourceMap源码映射设置
前端·webpack·node.js
Python私教1 小时前
Go语言现代web开发15 Mutex 互斥锁
开发语言·前端·golang
A阳俊yi1 小时前
Vue(13)——router-link
前端·javascript·vue.js
小明说Java1 小时前
Vue3祖孙组件通信探秘:运用provide与inject实现跨层级数据传递
前端
好看资源平台1 小时前
前端框架对比与选择:如何在现代Web开发中做出最佳决策
前端·前端框架
4triumph1 小时前
Vue.js教程笔记
前端·vue.js
程序员大金1 小时前
基于SSM+Vue+MySQL的酒店管理系统
前端·vue.js·后端·mysql·spring·tomcat·mybatis
清灵xmf1 小时前
提前解锁 Vue 3.5 的新特性
前端·javascript·vue.js·vue3.5
白云~️2 小时前
监听html元素是否被删除,删除之后重新生成被删除的元素
前端·javascript·html
金灰2 小时前
有关JS下隐藏的敏感信息
前端·网络·安全