不能错过!6个超实用的ReactHooks

373 阅读6分钟

全文共6229字,预计学习时长18分钟

图源:pexels

你还在为该使用无状态组件(Function)还是有状态组件(Class)而烦恼吗?

拥有了hooks,你再也不需要写Class了,你的所有组件都将是Function。

你还在为搞不清使用哪个生命周期钩子函数而日夜难眠吗?

拥有了Hooks,生命周期钩子函数就可以成为弃婴,先丢一边了。

你在还在为组件中的this指向而晕头转向吗?

既然Class都丢掉了,哪里还有this?有生之年第一次不再需要面对this。

React Hooks作为近两年最流行的新特性,为广大程序员同胞带来了便利。

如果你也对react感兴趣,或者正在使用react进行项目开发,那你绝对不能错过这篇文章,小芯为大家整理了6个超实用的便捷React Hooks函数。

图源:pexels

补充:了解一下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

准备开始

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>

2. @rehooks/window-scroll-position

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

@rehooks/window-scroll-position

安装

yarn add@rehooks/window-scroll-position

使用

import useWindowScrollPositionfrom '@rehooks/window-scroll-position'function MyComponent() {

// optionally you can pass options,those are default:

let options = {

throttle: 100,

}

let position = useWindowScrollPosition(options)

// position == { x: 0, y: 0 }

return <div />

}

3. @rehooks/local-storage

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

@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 = () => (

<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 文档可以从这里找到。

4. 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>

);

}

5. @rehooks/component-size

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

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

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

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

</div>

)

}

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

ResizeObserver browser support

6. use-onclickoutside

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

use-onclickoutside

入门指南

Yarn

yarn add use-onclickoutside

用法

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

import React, { useRef } from 'react'

import useOnClickOutside from 'use-onclickoutside'export default function Modal({close }) {

const ref = useRef(null)

useOnClickOutside(ref, close) return <div ref={ref}>{'Modalcontent'}</div>

}

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

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

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

留言 点赞 关注

我们一起分享AI学习与发展的干货
欢迎关注全平台AI垂类自媒体 “读芯术”


(添加小编微信:dxsxbb,加入读者圈,一起讨论最新鲜的人工智能科技哦~)