Skip to content

ahooks处理业务场景

1. ahooks业务场景介绍

ahooks提供具体使用中很多场景的hooks的钩子函数:
Alt text

2. 使用useHistoryTravel

useHistoryTravel钩子有两个非必须参数,第一个是初始值,第二个参数是历史记录最大长度。

jsx
import {  Button, Input, Space } from 'antd'
import { useHistoryTravel } from 'ahooks';

function App() {
  //设置记录历史最长6
  const {value, setValue, backLength, forwardLength, back, forward} =
    useHistoryTravel('', 6)

  return (
    <>
        <Space>
          <Input value={value || ''} onChange={(e) => setValue(e.target.value)}/>
          <Button type='primary' disabled={backLength <= 0 } onClick={back}>后退</Button>
          <Button type='primary' disabled={ forwardLength <= 0 } onClick={forward}>前进</Button>
        </Space>
    </>
  )
}

export default App

运行效果:
Alt text

3. 使用useDynamicList

useDynamicList可以方便的动态增删列表:

jsx
import { Input, Row, Space } from 'antd'
import { MinusCircleOutlined, PlusCircleOutlined } from '@ant-design/icons'
import { useDynamicList } from 'ahooks'

function App() {
  const { list, remove, getKey, insert, replace } = useDynamicList(['身份证长度18位', '手机号11位'])

  return (
    <>
      <h3>添加数据校验规则:</h3>
      <Row  gutter={[16, 8]}>
      {
        list.map((item, index) => (
          <Row key={getKey(index)}>
            <Space>
              <Input value={item} onChange={e => replace(index, e.target.value)}/>
              <MinusCircleOutlined onClick={() => remove(index)}/>
              <PlusCircleOutlined onClick={() => insert(index, '')}/>
            </Space>
          </Row>
        ))
      }
      </Row>
    </>
  )
}
export default App

运行效果:
Alt text