ReactJs: Prevent multiple times button press

前端 未结 9 984
别跟我提以往
别跟我提以往 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:59

    If you disable the button during onClick, you basically get this. A clean way of doing this would be:

    import React, { useState } from 'react';
    import Button from '@material-ui/core/Button';
    
    export default function CalmButton(props) {
        const [executing, setExecuting] = useState(false);
    
        const {
            disabled,
            onClick,
            ...otherProps
        } = props;
    
        const onRealClick = async (event) => {
            setExecuting(true);
            try {
                await onClick();
            } finally {
                setExecuting(false);
            }
        };
    
        return (
            

    See it in action here: https://codesandbox.io/s/extended-button-that-disabled-itself-during-onclick-execution-mg6z8

    We basically extend the Button component with the extra behaviour of being disabled during onClick execution. Steps to do this:

    1. Create local state to capture if we are executing
    2. Extract properties we tamper with (disabled, onClick)
    3. Extend onClick operation with setting the execution state
    4. Render the button with our overridden onClick, and extended disabled

    NOTE: You should ensure that the original onClick operation is async aka it is returning a Promise.

提交回复
热议问题