react-hooks-lib

2018-12-08 admin

A set of reusable React Hooks.

Hooks are a new feature proposal that lets you use state and other React features without writing a class. They’re currently in React v16.7.0-alpha and being discussed in an open RFC.

Installation

npm i react-hooks-lib --save

Examples

Visit here

Hooks

Name Arguments Returns
Lifecycles

| | | | useDidMount | f | - | | useWillUnmount | f | - | | useDidUpdate | f, conditions | - | |

State

| | | | useMergeState | initial | { state, set } | | useCounter | initial | { count, set, reset, inc, dec, incBy, decBy } | | useToggle | initial | { on, set, reset, toggle } | | useList | initial | { list, set, reset, push, sort, filter } | | useMap | initial | { values, set, reset, clear, get, has, delete } | |

Network

| | | | useFetch | initialUrl, initialOptions, onMount | { loading, data, error, fetch, setUrl, setOptions } | | useOnlineStatus | | | |

Feedback

| | | | useHover | - | { hovered, bind } | | useActive | - | { active, bind } | | useFocus | - | { focused, bind } | | useTouch | - | { touched, bind } | |

Data Entry

| | | | useField | initial | { value, set, reset, bind } |

API

useDidMount(f)

Similar to componentDidMount in React class component.

Arguments

  • f: () => void: f is called when component did mount.
import { useDidMount } from 'react-hooks-lib'

const MyComponent = () => {
  useDidMount(() => {
    console.log('didMount')
  })
}

useWillUnmount(f)

Close to the componentWillUnmount in React class component.

Arguments

  • f: () => void: f is called when component will unmount.
import { useWillUnmount } from 'react-hooks-lib'

const MyComponent = () => {
  useWillUnmount(() => {
    console.log('willUnmount')
  })
}

useDidUpdate(f, options?)

Similar to componentDidUpdate, it only runs on updates.

Arguments

  • f: () => Function | void: f is called on every updates. Like useEffect, f can return a clean-up function.
  • conditions?: Array<any>: Optional array for conditionally firing an effect, same as the second argument passed to useEffect.
import { useDidUpdate, useCounter } from 'react-hooks-lib'

const MyComponent = () => {
  const { count, inc } = useCounter(0)
  useDidUpdate(() => {
    console.log('DidUpdate')
  })
  return (
    <div>
      {`count: ${count}`}
      <button onClick={inc}>+1</button>
    </div>
  )
}

useMergeState(initial?)

Arguments

  • initial?: Object: Initial state object, default is {}.

Returns

  • state: Object: Current state object.
  • set: ((Object) => Object) | Object: Like setState in React class component, merge the old and new state together.
import { useMergeState } from 'react-hooks-lib'

const MergeState = () => {
  const { state, set } = useMergeState({ name: 'Victor', age: 1 })
  return (
    <div>
      <h3>useMergeState</h3>
      <div>
        {`state: ${JSON.stringify(state)}`}
        <button onClick={() => set(({ age }) => ({ age: age + 1 }))}>age+1</button>
      </div>
    </div>
  )
}

useCounter(initial)

import { useCounter } from 'react-hooks-lib'

const Counter = () => {
  const {
    count, inc, dec, reset,
  } = useCounter(1)
  return (
    <div>
      {count}
      <button onClick={inc}>+1</button>
      <button onClick={dec}>-1</button>
      <button onClick={reset}>reset</button>
    </div>
  )
}

useToggle(initial)

import { useToggle } from 'react-hooks-lib'

const Toggle = () => {
  const { on, toggle, reset } = useToggle(false)
  return (
    <div>
      {String(on)}
      <button onClick={toggle}>toggle</button>
      <button onClick={reset}>reset</button>
    </div>
  )
}

useList(initial)

import { useList } from 'react-hooks-lib'
const List = () => {
  const { list, sort, filter } = useList([1, 4, 2, 3, 4, 2, 6, 8, 3, 4])
  return (
    <div>
      list:
      {JSON.stringify(list)}
      <button onClick={() => sort((x, y) => x - y)}>sort</button>
      <button onClick={() => filter(x => x >= 4)}> greater than or equal to 4</button>
    </div>
  )
}

useMap(initial)

useFetch(initialUrl, initialOptions?, onMount?)

import { useField, useFetch } from 'react-hooks-lib'

const Fetch = () => {
  const getUrl = text => `https://api.github.com/search/repositories?q=${text}`
  const { value, bind } = useField('react')
  const { data, loading, setUrl } = useFetch(getUrl('react'))
  return (
    <div>
      <h3>useFetch</h3>
      <input type="text" value={value} {...bind} />
      <button onClick={() => {
        setUrl(getUrl(value))
      }}
      >
        search
      </button>
      {
        loading
          ? <div>Loading...</div>
          : (<span>{`total_count: ${data.total_count}`}</span>)
      }
    </div>
  )
}

useOnlineStatus()

useHover()

import { useHover } from 'react-hooks-lib'

const Hover = () => {
  const { hovered, bind } = useHover()
  return (
    <div>
      <div {...bind}>
        hovered:
        {String(hovered)}
      </div>
    </div>
  )
}

useActive()

useFocus()

useTouch()

useField(initial)

  import {useField} from 'react-hooks-lib'

  const Input = () => {
    const { value, bind } = useField('Type Here...')

    return (
      <div>
        input text:
        {value}
        <input type="text" {...bind} />
      </div>
    )
  }

  const Select = () => {
    const { value, bind } = useField('apple')
    return (
      <div>
        selected:
        {value}
        <select {...bind}>
          <option value="apple">apple</option>
          <option value="orange">orange</option>
        </select>
      </div>
    )
  }

原文链接:https://github.com/beizhedenglong/react-hooks-lib

本站文章除注明转载外,均为本站原创或编译。欢迎任何形式的转载,但请务必注明出处。

转载请注明:文章转载自 JavaScript中文网 [https://www.javascriptcn.com]

本文地址:https://www.javascriptcn.com/read-47571.html

文章标题:react-hooks-lib

相关文章
超级给力的JavaScript的React框架入门教程
React 是 Facebook 里一群牛 X 的码农折腾出的牛X的框架。 实现了一个虚拟 DOM,用 DOM 的方式将需要的组件秒加,用不着的秒删。React 扮演着 MVC 结构中 V 的角色, 不过你要是 Flux 搭配使用, 你就有...
2017-03-27
create-react-app配置多页应用
背景:最近接手一个混合app项目,但是其中的页面都是用jquery写的,有点乱,所以决定用react重构一下,因为涉及到很多页面,所以create-react-app只能自己配置成多页的了。弄这个也弄了挺久的,主要是对webpack的各个...
2018-01-10
Reactjs实现通用分页组件的实例代码
大家多少都自己写过各种版本的分页工具条吧,像纯服务版的,纯jsWeb板的,Angular版的,因为这个基础得不能再基础的功能太多地方都会用到,下面我给出以个用ReactJS实现的版本,首先上图看下效果: 注意这个组件需要ES6环境,最好使...
2017-03-01
React水印组件,支持图片水印,文字水印
React水印组件,支持图片水印,文字水印。 安装 npm i --save react-watermark-module 用法 import ReactWatermark from &#x27;react-watermark-modul...
2018-01-09
webpack全家桶+react全家桶项目实战(集成antd)
原文链接 项目开始前,我们先聊一聊关于项目的一些说明。该项目起始于2017年初,当时公司主要技术栈为gulp+angular,鉴于react的火热的生态,在公司决定研发bss管理系统时选用react开发,目的也是为react native打...
2018-02-26
react性能优化达到最大化的方法 immutable.js使用的必要性
一行代码胜过千言万语。这篇文章呢,主要讲述我一步一步优化react性能的过程,为什么要用immutable.js呢。毫不夸张的说。有了immutable.js(当然也有其他实现库)。。才能将react的性能发挥到极致!要是各位看官用过一段时...
2017-03-14
利用ES6语法重构React组件详解
一、创建组件 ES6 class创建的组件语法更加简明,也更符合javascript。内部的方法不需要使用function关键字。 React.createClass import React from &#x27;react&#x27;;...
2017-03-14
React实战篇(React仿今日头条)
前言 上次初学用 react 写了个后台管理,这次便寻思写个移动端的项目。便有了这次的这个项目。 这个项目以前写了个 vue 的版本。有兴趣的可以 点击进入 模拟数据用的是 Easy Mock 用的是我以前写 vue-toutiao 用到的...
2018-04-09
React-Navigation 导航综合应用
本文由我们团队的 杨俊宁 组内分享后总结。 移动应用中最常见的导航风格可能是基于 tab 的导航。 可以在屏幕底部或顶部的标题栏下方(甚至取代标题栏)。 createStackNavigator 创建的 stack navigator...
2018-06-27
使用 React 和 Django REST Framework 构建你的网站
此专栏我会不定期分享一些 Django 最前沿的文章,内容偏重技巧、经验的归纳总结,来源暂时有: Medium Twitter 知名博主 如果大家感兴趣,请一定点个关注,给我一些动力,毕竟翻译整理是需要时间的,谢谢大家 – 原文地址:...
2018-02-08
回到顶部