ReactJs: Prevent multiple times button press

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

    The solution is to check the state immediately upon entry to the handler. React guarantees that setState inside interactive events (such as click) is flushed at browser event boundary. Ref: https://github.com/facebook/react/issues/11171#issuecomment-357945371

    // In constructor
    this.state = {
        disabled : false
    };
    
    
    // Handler for on click
    handleClick = (event) => {
        if (this.state.disabled) {
            return;
        }
        this.setState({disabled: true});
        // Send     
    }
    
    // In render
    

提交回复
热议问题