ReactJs: Prevent multiple times button press

前端 未结 9 980
别跟我提以往
别跟我提以往 2020-11-27 13:21

In my React component I have a button meant to send some data over AJAX when clicked. I need to happen only the first time, i.e. to disable the button after it\'s first use.

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 13:50

    const once = (f, g) => {
        let done = false;
        return (...args) => {
            if (!done) {
                done = true;
                f(...args);
            } else {
                g(...args);
            }
        };
    };
    
    const exampleMethod = () => console.log("exampleMethod executed for the first time");
    const errorMethod = () => console.log("exampleMethod can be executed only once")
    
    let onlyOnce = once(exampleMethod, errorMethod);
    onlyOnce();
    onlyOnce();
    

    output

    exampleMethod executed for the first time
    exampleMethod can be executed only once
    

提交回复
热议问题