<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          推薦十一個React Hook庫

          共 8308字,需瀏覽 17分鐘

           ·

          2021-06-14 16:26

          Hooks來了,并在暴風雨中占領了React社區(qū)。自最初發(fā)布以來已經(jīng)有一段時間了,這意味著有很多支持庫。在搜索與React相關的內(nèi)容時,很難不說“ hook”。如果你們還沒有使用它的話,應該盡快將它們加入代碼庫。它們將使您的編碼生活變得更加輕松和愉快。

          在React開發(fā)中,保持干凈的代碼風格,可讀性,可維護性,更少的代碼行以及可重用性至關重要。本篇文章將向您介紹應立即開始使用的十一個React Hook庫。不用再拖延了,讓我們開始吧。

          1.use-http

          use-http是一個非常有用的軟件包,可用來替代Fetch API。以高質(zhì)量編寫和維護。它使您的編碼更簡單易懂,更精確地講是數(shù)據(jù)處理部分。hook本身使用TypeScript,甚至支持SSR和GraphQL。它返回響應,加載,錯誤數(shù)據(jù)和不同的請求方法,例如Get,Post,Put,Patch和Delete。

          它提供的主要功能是:

          • 請求/響應攔截器
          • 支持React Native
          • 卸載組件時中止/取消掛起的http請求
          • 緩存

          CodeSandbox示例和Youtube視頻以及GitHub自述文件都對此進行了很好的記錄。

          官網(wǎng)地址:

          https://use-http.com/#/

          使用案例

          import useFetch from "use-http"

          const Example = () => {
          const [todos, setTodos] = useState([])
          const { get, post, response, loading, error } = useFetch("https://example.com")

          useEffect(() => { get("/todos") }, [])

          const addTodo = async () => {
          await post("/todos", { title: "example todo" });
          if (response.ok) setTodos([...todos, newTodo])
          }

          return (
          <>
          <button onClick={addTodo}>Add Todo</button>
          {error && 'Error!'}
          {loading && 'Loading...'}
          {todos.map(todo => (
          <span key={todo.id}>{todo.title}</span>
          )}
          </>

          );
          };

          2.useMedia

          您是否需要一種跟蹤CSS媒體查詢的方法?該useMedia hook提供一個簡單的方法解決問題。這是一個準確跟蹤React sensor hook。媒體查詢以及任何應用程序或網(wǎng)站的響應能力都非常重要。

          它提供了支持TypeScript編寫。該軟件包具有定義明確的文檔,其中解釋了掛鉤的用法以及測試方法。

          地址:

          https://github.com/streamich/use-media

          使用案例:

          import useMedia from 'use-media';

          const Example = () => {
          const isWide = useMedia({minWidth: '1000px'});

          return (
          <span>
          Screen is wide: {isWide ? "WideScreen" : "NarrowScreen"}
          </span>

          );
          };

          3.Constate

          Constate是一個hook package,可將本地狀態(tài)提升到React Context。這意味著可以以最小的努力輕松地將任何組件的任何狀態(tài)提升到上下文。如果您想在多個位置使用相同的狀態(tài),或者為多個組件提供相同的狀態(tài),這很有用。該名稱來自合并上下文和狀態(tài)的文字游戲。使用Typescript寫的,體積很小。雖然該文檔不是很詳細,但是可以完成工作。

          地址:

          https://github.com/diegohaz/constate

          使用案例:

          import React, { useState } from "react";
          import constate from "constate";

          // custom hook
          function useCounter() {
          const [count, setCount] = useState(0);
          const increment = () => setCount(prevCount => prevCount + 1);
          return { count, increment };
          }

          // hook passed in constate
          const [CounterProvider, useCounterContext] = constate(useCounter);

          function Button() {
          // use the context
          const { increment } = useCounterContext();
          return <button onClick={increment}>+</button>;
          }

          function Count() {
          // use the context
          const { count } = useCounterContext();
          return <span>{count}</span>;
          }

          function App() {
          // wrap the component with provider
          return (
          <CounterProvider>
          <Count />
          <Button />
          </CounterProvider>

          );

          4.Redux hooks

          Redux是許多(即使不是全部)React開發(fā)人員的知名工具。在整個應用程序中,它用作全局狀態(tài)管理器。在React的最初版本發(fā)布幾個月后,它就隨鉤而上了。它通過現(xiàn)有connect()方法提供了HOC(高階組件)模式的替代方法。

          提供的最著名的hooks是:

          • useSelector
          • useDispatch
          • useStore

          該文檔非常好,有點復雜,但是它將為您提供開始使用它們所需的任何信息。

          地址:

          https://github.com/reduxjs/redux

          使用案例:

          import {useSelector, useDispatch} from "react-redux";
          import React from "react";
          import * as actions from "./actions";

          const Example = () => {
          const dispatch = useDispatch()
          const counter = useSelector(state => state.counter)

          return (
          <div>
          <span>
          {counter.value}
          </span>
          <button onClick={() => dispatch(actions.incrementCounter)}>
          Counter +1
          </button>
          </div>

          );
          };

          5.React hook form

          React hook form是一個與Formik和Redux表單相似的表單校驗hook庫,但是更好!憑借其更簡單的語法,速度,更少的轉(zhuǎn)譯和更好的可維護性,它開始爬上GitHub的階梯。它的體積很小,并且考慮到性能而構(gòu)建。該庫甚至提供了它的表單生成器,這很棒!它是React鉤子庫(14.8k)中GitHub啟動數(shù)量最多的平臺之一。

          它提供的主要功能:

          • 非受控表單校驗
          • 以性能和開發(fā)體驗為基礎構(gòu)建
          • 迷你的體積而沒有其他依賴
          • 遵循 html 標準進行校驗
          • 與 React Native 兼容
          • 支持瀏覽器原生校驗

          地址:

          https://github.com/react-hook-form/react-hook-form

          使用案例:

          import React from "react";
          import { useForm } from "react-hook-form";

          function App() {
          const { register, handleSubmit, errors } = useForm();
          const onSubmit = (data) => {
          // logs {firstName:"exampleFirstName", lastName:"exampleLastName"}
          console.log(data);
          };

          return (
          <form onSubmit={handleSubmit(onSubmit)}>
          <input name="firstName" ref={register} />
          <input name="lastName" ref={register({ required: true })} />
          {errors.lastName && <span>"Last name is a required field."</span>}
          <input name="age" ref={register({ required: true })} />
          {errors.age && <span>"Please enter number for age."</span>}
          <input type="submit" />
          </form>

          );
          }

          6.useDebounce

          useDebounce 表示一個用于去抖的小鉤子。它用于將功能執(zhí)行推遲到以后。常用于獲取數(shù)據(jù)的輸入和表格中。

          地址:

          https://github.com/xnimorz/use-debounce

          使用案例:

          import React, { useState } from "react";
          import { useDebounce } from "use-debounce";

          export default function Input() {
          const [text, setText] = useState("Hello");
          const [value] = useDebounce(text, 1000);

          return (
          <div>
          <input
          defaultValue={"Hello"}
          onChange={(e) =>
          {
          setText(e.target.value);
          }}
          />
          <p>Value: {text}</p>
          <p>Debounced value: {value}</p>
          </div>

          );
          }

          7.useLocalStorage

          useLocalStorage是一個小鉤子,與上面的鉤子一樣。這對于在localStorage中提取和設置數(shù)據(jù)非常有用。操作變得容易。提供跨多個選項卡的自動JSON序列化和同步,并以TypeScript編寫,因此它提供了類型。

          文檔以高質(zhì)量的方式編寫,并且可以通過擴展示例來很好地理解。

          地址:

          https://github.com/rehooks/local-storage

          使用案例:

          import React, { useState } from "react";
          import { writeStorage } from '@rehooks/local-storage';

          export default function Example() {
          let counter = 0;
          const [counterValue] = useLocalStorage('counterValue');

          return (
          <div>
          <span>{counterValue}</span>
          <button onClick={() => writeStorage('i', ++counter)}>
          Click Me
          </button>
          </div>

          );
          }

          8.usePortal

          usePortal 使創(chuàng)建下拉菜單,模態(tài),通知彈出窗口,工具提示等變得非常容易!它提供了在應用程序的DOM層次結(jié)構(gòu)之外創(chuàng)建元素的信息(react docs)。該鉤子與SSR一起使用,因為它是同構(gòu)的。用TypeScript編寫并具有內(nèi)置狀態(tài)。它還提供了portals樣式和大量其他選項的完全定制。

          為此編寫的文檔非常好,其中顯示了許多示例,這些示例對于開始使用庫/自己做鉤子來說綽綽有余。

          地址:

          https://github.com/alex-cory/react-useportal

          使用案例:

          import React, { useState } from "react";
          import usePortal from "react-useportal";

          const Example = () => {
          const { ref, openPortal, closePortal, isOpen, Portal } = usePortal()

          return (
          <>
          <button ref={ref} onClick={() => openPortal()}>
          Open Portal
          </button>
          {isOpen && (
          <Portal>
          <p>
          This Portal handles its own state.{' '}
          <button onClick={closePortal}>Close me!</button>, hit ESC or
          click outside of me.
          </p>
          </Portal>
          )}
          </>

          )
          }

          9.useHover

          useHover是一個React state hook,它確定是否正在hover React元素。簡單易用。該庫很小,易于使用,但如果您有足夠的創(chuàng)造力,它可能會很強大。

          它還提供了懸停效果的延遲。支持TypeScript。文檔沒有那么詳細,但是它將向您展示如何正確地使用它。

          地址:

          https://github.com/andrewbranch/react-use-hover

          使用案例:

          import useHover from "react-use-hover";

          const Example = () => {
          const [isHovering, hoverProps] = useHover();
          return (
          <>
          <span {...hoverProps} aria-describedby="overlay">Hover me</span>
          {isHovering ? <div> I’m a little tooltip! </div> : null}
          </>

          );
          }

          10.React router hooks

          React router hooks是React最受歡迎的庫之一。它用于路由和獲取應用程序URL歷史記錄等。它與Redux一起實現(xiàn)了用于獲取此類有用數(shù)據(jù)的hook。

          它提供的主要功能是:

          • useHistory
          • useLocation
          • useParams
          • useRouteMatch

          它的名字很不言自明。UseHistory將獲取應用程序歷史記錄和方法的數(shù)據(jù),例如push推送到新路由。UseLocation將返回代表當前URL的對象。UseParams將返回當前路徑的URL參數(shù)的鍵-值對的對象。最后,useRouteMatch將嘗試將當前URL與給定URL進行匹配,給定URL可以是字符串,也可以是具有不同選項的對象。

          文檔很好,寫了很多例子

          地址:

          https://github.com/ReactTraining/react-router

          使用案例:

          import { useHistory, useLocation, useRouteMatch } from "react-router-dom";

          const Example = () => {
          let history = useHistory();
          let location = useLoction();
          let isMatchingURL = useRouteMatch("/post/11");

          function handleClick() {
          history.push("/home");
          }

          return (
          <div>
          <span>Current URL: {location.pathname}</span>
          {isMatchingURL ? <span>Matching provided URL! Yay! </span> : null}
          <button type="button" onClick={handleClick}>
          Go home
          </button>
          </div>

          );
          }

          11.react-use

          react-use是一個必不可少的 React Hooks集合.你需要安裝React 16.8.0或更高版本才能使用Hooks API。

          地址:

          github.com/streamich/react-use

          使用案例:

          import {useBattery} from 'react-use';

          const Demo = () => {
          const state = useBattery();

          return (
          <pre>
          {JSON.stringify(state, null, 2)}
          </pre>

          );
          };

          當前還有更多的鉤子庫,找到適合自己使用的就是最好的,不僅提高了開發(fā)的效率,而且讓代碼更加整潔,簡單。


          瀏覽 101
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  免费性爱视频网站 | 最近2019中文字幕mv第三季歌词 | 国产精品毛片一区视频播 | 婷婷色在线视频 | 国产精品久久久久久久久久久久久久 |