kn-hooks

0.0.32 • Public • Published

kn-hooks

目录

使用方法

npm i kn-hooks
// 务必使用 {指定模块名} 来引用触发tree-shake 
import {useClipboard} from 'kn-hooks';

const Index=()=>{
  const clip = useClipboard();
}

按需打包

webpack4及以上版本无需下面配置

webpack增加bable-plugin-import插件,给babel plugins增加配置

//  rules: [
//     {
//       test: /\.js[x]?$/,
//       exclude: /node_modules/,
//       use: {
//         loader:'babel-loader',
//         options:{
//           plugins: [
              [
                import, { 
                  libraryName: "kn-hooks" ,
                  camel2DashComponentName:false,
                  libraryDirectory:"src",
                }
              ]
//           ]
//         }
//       }
//     }
//  ]

API

G useClipboard

M useClipboard([props]) ⇒ UseClipboardResult

剪贴板工具

Demo - CodeSandBox

Param Type Description
[props] Object -
[props.onSuccess] callback 成功复制到剪贴板后的回调 ()=>void

Example

const clipboard= useClipboard();
const onCopy=()=>{
  clipboard('text',()=>{console.log('success')})
}

T FunCopy : callback

复制函数

Properties

Name Type Description
text string 需要被复制的字符串
onCurSuccess callback 复制成功的回调 ()=>void

T UseClipboardResult : Object

UseClipboardResult返回的hook

Properties

Name Type Description
copy FunCopy 触发复制字符串的函数

G useCounter

M useCounter() ⇒ UseCounterResult

加法计数器

Example

const counter= useCounter();
const onAdd=()=>{counter.addCount()}
return <span>当前计数器:{counter.count}</span>

T UseCounterResult

Properties

Name Type Description
req Object
req.count number 当前计数器的值
req.addCount function 计数器的值+1。 ()=>void

G useDictionary

M SetConfig(params) ⇒ void

全局设置SelectOption和RadioOption

Param Type Description
params Object
params.SelectOption ReactDom Antd的SelectOption组件
params.RadioOption ReactDom Antd的SelectOption组件

Example

import {useDictionary} from 'kn-hooks';
  import {Select,Radio} from 'antd';
  useDictionary.SetConfig({SelectOption:Select.Option,RadioOption:Radio.Option});

M createDictionary(options) ⇒ callback

创建字典hooks工具

Param Type Default Description
options Object
options.api Api 用于获取字典列表的接口
[options.idKey] string "'id'" 字段id的key键值
[options.nameKey] string "'name'" 字段name的key键值
[options.labelKey] string "'label'" 字段label的key键值
[options.SelectOption] ReactDom 指定<Select.Option>对象是谁
[options.RadioOption] ReactDom 指定<Radio.Button>对象是谁
[options.beforeApi] callback (request:object)=>object 接口调用前的参数拦截器
[options.afterApi] callback (reponse:object)=>object[] 接口调用后的拦截器
[options.defaultTypes] Array.<DictionaryItem> 如果字典不是通过api获取,可以在这里设置字典的内容

Example

// emUserType.jsx
    import {useDictionary} from 'kn-hooks';
  export const userType = useDictionary.createDictionary({
    api:()=>Promise.resolve({
      code:0,
      data:{
        body:[{id:'1001',label:'项目1001',name:'pm1001'},],
      }
    }),
    afterApi:(response)=>{
      let list;
      if(response?.code==0){
        list= response?.data?.body?.map(item=>{...})
      }
      return list;
    }
  });
  // index.jsx
  import {userType} from './emUserType.jsx'
  const Page=()=>{
    const emUserType = userType();
    return (
      <section>
        <Select defaultValue={emUserType.getId('项目1001')}>
        {emUserType.selectOptions}
        </Select>
      </section>
    )
  }

M useDictionary(props) ⇒ UseDictionaryResult

字典管理

Demo - CodeSandBox

Param Type Default Description
props Object
props.api Api 用于获取字典列表的接口
[props.idKey] string "'id'" 字段id的key键值
[props.nameKey] string "'name'" 字段name的key键值
[props.labelKey] string "'label'" 字段label的key键值
[props.SelectOption] ReactDom 指定<Select.Option>对象是谁
[props.RadioOption] ReactDom 指定<Radio.Button>对象是谁
[props.beforeApi] callback (request:object)=>object 接口调用前的参数拦截器
[props.afterApi] callback (reponse:object)=>object[] 接口调用后的拦截器
[props.defaultTypes] Array.<DictionaryItem> 如果字典不是通过api获取,可以在这里设置字典的内容

Example

import {Select,Radio} from 'antd';
import useDictionary,{SetConfig} from '@/useDictionary';
SetConfig({SelectOption:Select.Option,RadioOption:Radio.Button});

const Index=()=>{

  const emCity = useDictionary({
    api:()=>{
        return new Promise(resolve=>{
          resolve({
            code:0,
            data:{
              body:[
                {id:1,name:'shanghai',label:'上海'},
                {id:2,name:'beijing',label:'北京'},
                {id:3,name:'guangzhou',label:'广州'}
              ]
            }
          })
        })
      }
  });

  return (
    <section >
      <Select defaultValue={1}>
        {
          emCity.selectOptions
        }
      </Select>
      <p>分割线</p>
      <Radio.Group defaultValue={1}>
        {
          emCity.radioOptions
        }
      </Radio.Group>
    </section>
  )
}

T Api ⇒ Object

Properties

Name Type Description
params Object 调用接口用到的参数

T DictionaryItem

Properties

Name Type Description
id string 数据唯一ID
name string 数据唯一id对应的别名
label string 展示给用户看的文字

T UseDictionaryResult

Properties

Name Type Description
types Array.<DictionaryItem> 字典数据列表
selectOptions Array.<ReactDOM> 供Antd渲染<Select>的列表
radioOptions Array.<ReactDOM> 供Antd渲染<Radio>的列表
getId function (labelOrName:string)=>string,搜索字典项中,label或name匹配labelOrName的项目,返回其id的值
getName function (id:string)=>string,搜索字典项中,id匹配id的项目,返回其name的值
getLabel function (id:string)=>string,搜索字典项中,id匹配id的项目,返回其label的值
reload function ()=>void,重新调用字典接口刷新字典列表

G usePagination

M usePagination(props) ⇒ UsePaginationResult

分页管理器

Version: 1.0.1

Param Type Description
props Object
props.service FunServices 发送请求的方法
[props.pagination] Pagination 默认分页信息
[props.beforeService] Array.<function()> api调用前监听方法列表
[props.afterService] Array.<function()> api调用后监听方法列表

Example

// 移动端滚动加载案例
  const page = usePagination({
    service:GET_LIST,
    pagination:{pageSize:10},
  });

  useEffect(()=>{
    // beforeService和afterService监听方法也可以直接设置在props内

    const fnFeforeService = (params)=>{
      // 假如你这里需要变更接口字段名称的话
      params.page=params.current;
      params.keyword='abc';
      return params;
    }
    
    const fnAfterService = (response)=>{
      // 这里你可以翻译及二次处理你的接口字段
      let req={
        code:response.errorCode
        data:response.list,
        page:response.pageInfo
      };
      return req;
    },

    page.addListener('beforeService',fnFeforeService);
    page.addListener('afterService',fnAfterService);
    return ()=>{
      page.removeListener('beforeService',fnFeforeService);
      page.removeListener('afterService',fnAfterService)
    }
  },[])

  const onReset=()=>{page.reset();}

  const onPageChange=()=>{
    let value=document.querySelector('#inputPage').value;
    page.update({pagination:{current:+value}})
  }
  const onNext=()=>{page.nextPage();}

  const renderTable=()=>{
    let renderData= [];
    page?.data?.forEach(list=>{
      renderData=[...renderData,...list];
    })
    
    return (
      <ul>
      {
        renderData?.map((item,idx)=>{
          return <li key={idx}>[{idx}]{item}</li>
        })
      }
      </ul>
    )
    
  }
  return (
    <ul>
    {renderTable()}
    </ul>
  )

M FunServices() ⇒ FunServicesCallback

分页请求接口格式要求

Properties

Name Type Default Description
current number 1 页码
pageSize number 10 分页大小
...others any 其它接口附带参数

T FunServicesCallback : Object

分页接口请求结果

Properties

Name Type Default Description
code number 0 接口调用结果,0为成功
data Array.<Object> 分页数据
page Object 分页信息
page.current number 页码
page.pageSize number 分页大小
page.total number 数据总量

T Pagination : Object

分页信息

Properties

Name Type Default Description
pageSize number 20 分页大小
current number 1 当前页码
total number 1 总记录数
[startIdx] number 0 当前页面下第一条数据的序号
[more] boolean 是否还有下一页

T PageDataResult : Object

分页数据结果

Properties

Name Type Description
pagination Pagination 最新分页信息
data Array.<Array.<Object>> 分页数据集合

T FunUpdate ⇒ Promise.<PageDataResult>

分页查询结果

Returns: Promise.<PageDataResult> - 最新的分页数据结果
Properties

Name Type Description
[pagination] Pagination 最新分页信息
[clear] boolean 是否清空数据

T UsePaginationResult : Object

usePagination的返回对象

Properties

Name Type Description
data Array.<Array.<Object>> 分页数据集合
pagination Pagination 分页信息
update FunUpdate 查询方法
next FunUpdate 获取下一页数据
addListener function 监听事件 (type='beforeService'
removeListener function 移除监听事件 (type,fn:FunListener)=>void
loading object loading状态,它是一个useSwitch

T FunListener ⇒ Object | Promise.<Object>

事件监听方法

Returns: Object | Promise.<Object> - 处理完毕的数据对象或者Promise
Properties

Name Type Description
params Object 被拦截的数据对象

G usePaginationWithForm

M usePaginationWithForm(props) ⇒ UsePaginationWithFormResult

支持Antd-Form的usePagination 作用是在查询接口前自动获取form表单内的字段,并作为接口查询参数进行查询 使用方法及参数字段参考 usePagination

Param Type Description
props Object
props.form Object Form表单的ref,在接口调用前会校验获取form表单内的数据,提交到接口参数内查询

Example

const [form] = Form.useForm();
const page = usePaginationWithForm({
  service:GET_LIST,
  pagination:{pageSize:10},
  form:form
});

const onSearch=()=>{
  page.update();
}
const onReset=()=>{
  page.reset();
}
return(
  <Form form={form} style={{width:'600px'}} layout="inline">
    <Form.Item label='关键字' name='keyword' rules={[
      {
        max:5,
        message:'最多5个字符'
      }
    ]}>
      <Input />
    </Form.Item>
    <Button onClick={onSearch} type='primary'>查询</Button>
    <Button onClick={onReset} type='primary'>重置</Button>
  </Form>
)

T UsePaginationWithFormResult : Object

usePaginationWithForm的返回对象

Properties

Name Type Description
reset function 重置方法,返回Promise

G useSwitch

useSwitch

M useSwitch([props]) ⇒ UseSwitchResult

控制开关

Demo-CodeSandbox

Param Type Default Description
[props] boolean false 默认的开关状态

T UseSwitchResult : Object

useSwitchHookResult

Properties

Name Type Description
state boolean 当前开关状态
count number 当前开关计数器
open function 切换至开模式 (force?:boolean)=>void
close function 切换至关模式 (force?:boolean)=>void
toggle function 切换至反向模式 ()=>void

Readme

Keywords

none

Package Sidebar

Install

npm i kn-hooks

Weekly Downloads

16

Version

0.0.32

License

none

Unpacked Size

138 kB

Total Files

26

Last publish

Collaborators

  • knplugin