如何在 input 文件选择弹窗打开前做点事情呢?

80 阅读1分钟

背景

在开发H5的时候,在点击选择上传文件弹窗前,提前去注册端上的 JSB 能力来做上传处理。

实现原理

通过阻止事件的默认行为,来达到目标。event.preventDefault()

代码实现

React

import { useCallback, useRef } from "react";

export default function App() {
    const inputRef = useRef(null);
    const stopPreventRef = useRef(true);

    const onClick = useCallback(async (event) => {
        if (stopPreventRef.current) {
            event.preventDefault();
            stopPreventRef.current = false;
            await new Promise((resolve) => {
                console.log("可以做一些事情了");
                setTimeout(() => resolve(), 2000);
            });
            inputRef.current.click();
            return;
        }
        stopPreventRef.current = true;
    }, []);

    return (
        <div className="App">
        <input
            ref={inputRef}
            id="input"
            type="file"
            onClick={onClick}
            />
        </div>
    );
}