详细讲一下ahooks中的好用方法(11-20),非常干货

我们继续ahooks的专栏,希望能帮助到大家! 

1.useClickAway - 点击外部区域处理

import { useClickAway } from 'ahooks'

function Demo() {
    const ref = useRef(null)
    const [visible, setVisible] = useState(false)
    
    // 点击目标元素外部时触发
    useClickAway(() => {
        setVisible(false)  // 关闭弹窗
    }, ref)
    
    return (
        <div>
            <button onClick={() => setVisible(true)}>
                打开弹窗
            </button>
            {visible && (
                <div ref={ref} style={{ border: '1px solid' }}>
                    点击外部关闭的弹窗
                </div>
            )}
        </div>
    )
}

2.useEventListener - 事件监听:

import { useEventListener } from 'ahooks'

function Demo() {
    // 监听窗口大小变化
    useEventListener('resize', () => {
        console.log('窗口大小变化了')
    })
    
    // 监听元素点击
    const ref = useRef(null)
    useEventListener(
        'click',
        (e) => {
            console.log('元素被点击了', e)
        },
        { target: ref }
    )
    
    return <button ref={ref}>点击我</button>
}

3.usePrevious - 获取上一次的值:

import { usePrevious } from 'ahooks'

function Demo() {
    const [count, setCount] = useState(0)
    // 获取 count 的上一次值
    const prevCount = usePrevious(count)
    
    return (
        <div>
            <p>当前值: {count}</p>
            <p>上一次的值: {prevCount}</p>
            <button onClick={() => setCount(c => c + 1)}>
                增加
            </button>
        </div>
    )
}

 4.useHover - 鼠标悬停状态:

import { useHover } from 'ahooks'

function Demo() {
    const ref = useRef(null)
    // 监听元素的悬停状态
    const isHovering = useHover(ref)
    
    return (
        <div
            ref={ref}
            style={{
                padding: 20,
                background: isHovering ? '#e6f7ff' : '#fff',
                transition: 'all 0.3s'
            }}
        >
            {isHovering ? '鼠标悬停中' : '鼠标移入试试'}
        </div>
    )
}

5.useSetState - 对象状态管理:

import { useSetState } from 'ahooks'

function Demo() {
    // 类似 class 组件的 setState
    const [state, setState] = useSetState({
        name: '',
        age: 0,
        nested: {
            foo: 'bar'
        }
    })
    
    return (
        <div>
            <input
                value={state.name}
                onChange={e => setState({ name: e.target.value })}
            />
            <button
                onClick={() => setState(prev => ({
                    age: prev.age + 1
                }))}
            >
                增加年龄
            </button>
            <button
                onClick={() => setState({
                    nested: { foo: 'baz' }
                })}
            >
                更新嵌套值
            </button>
        </div>
    )
}

6.useThrottle - 节流值:

import { useThrottle } from 'ahooks'

function Demo() {
    const [value, setValue] = useState('')
    // 节流后的值,500ms 内只会更新一次
    const throttledValue = useThrottle(value, { wait: 500 })
    
    return (
        <div>
            <input
                value={value}
                onChange={e => setValue(e.target.value)}
                placeholder="快速输入试试"
            />
            <p>节流后的值: {throttledValue}</p>
        </div>
    )
}

7.useControllableValue - 受控组件值:

import { useControllableValue } from 'ahooks'

function Demo({ value, onChange }) {
    // 自动处理受控和非受控状态
    const [state, setState] = useControllableValue(props, {
        defaultValue: '',  // 默认值
    })
    
    return (
        <input
            value={state}
            onChange={e => setState(e.target.value)}
        />
    )
}

8.useDynamicList - 动态列表管理

import { useDynamicList } from 'ahooks'

function Demo() {
    // 管理动态列表
    const { list, push, remove, getKey } = useDynamicList(['初始项'])
    
    return (
        <div>
            <button onClick={() => push('新项目')}>
                添加项目
            </button>
            {list.map((item, index) => (
                <div key={getKey(index)}>
                    {item}
                    <button onClick={() => remove(index)}>
                        删除
                    </button>
                </div>
            ))}
        </div>
    )
}

9.useResponsive - 响应式设计

import { useResponsive } from 'ahooks'

function Demo() {
    // 获取当前屏幕尺寸信息
    const responsive = useResponsive()
    
    return (
        <div>
            <p>当前屏幕尺寸:</p>
            {responsive.sm && <p>小屏幕</p>}
            {responsive.md && <p>中等屏幕</p>}
            {responsive.lg && <p>大屏幕</p>}
            {responsive.xl && <p>超大屏幕</p>}
        </div>
    )
}

10.useEventEmitter - 事件发布订阅:

import { useEventEmitter } from 'ahooks'

// 创建事件对象
const event$ = useEventEmitter()

// 组件 A:发布事件
function ComponentA() {
    return (
        <button onClick={() => event$.emit('hello', 'world')}>
            发送消息
        </button>
    )
}

// 组件 B:订阅事件
function ComponentB() {
    useEffect(() => {
        // 订阅事件
        const unsubscribe = event$.subscribe((data) => {
            console.log('收到消息:', data)
        })
        
        // 清理订阅
        return unsubscribe
    }, [])
    
    return <div>接收消息的组件</div>
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值