ReactJs: Prevent multiple times button press

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

    You can get the element reference in the onClick callback and setAttribute from there, eg:

          <Button
            onClick={(e) => {
              e.target.setAttribute("disabled", true);
              this.handler();
            }}            
          >
            Submit
          </Button>
    
    0 讨论(0)
  • 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
    <button onClick={this.handleClick} disabled={this.state.disabled} ...>
        {this.state.disabled ? 'Sending...' : 'Send'}
    <button>
    
    0 讨论(0)
  • 2020-11-27 13:44

    By using event.target , you can disabled the clicked button. Use arrow function when you create and call the function onClick. Don't forget to pass the event in parameter.

    See my codePen

    Here is the code:

    class Buttons extends React.Component{
      constructor(props){
        super(props)
        this.buttons = ['A','B','C','D']
      }
    
      disableOnclick = (e) =>{
        e.target.disabled = true
      }
    
      render(){
        return(
    
         <div>
            {this.buttons.map((btn,index) => (
              <button type='button' 
                key={index} 
                onClick={(e)=>this.disableOnclick(e)}
                >{btn}</button>
            ))}
          </div>
      )}
    
    }
    ReactDOM.render(<Buttons />, document.body);
    
    0 讨论(0)
  • 2020-11-27 13:45

    If you want, just prevent to submit.

    How about using lodash.js debounce

    Grouping a sudden burst of events (like keystrokes) into a single one.

    https://lodash.com/docs/4.17.11#debounce

    <Button accessible={true}
        onPress={_.debounce(async () => {
                    await this.props._selectUserTickets(this.props._accountId)
        }, 1000)}
    ></Button>
    
    0 讨论(0)
  • 2020-11-27 13:47

    What you could do is make the button disabled after is clicked and leave it in the page (not clickable element).

    To achieve this you have to add a ref to the button element

    <button ref="btn" onClick={this.onClickUploadFile}>Send</button>
    

    and then on the onClickUploadFile function disable the button

    this.refs.btn.setAttribute("disabled", "disabled");
    

    You can then style the disabled button accordingly to give some feedback to the user with

    .btn:disabled{ /* styles go here */}
    

    If needed make sure to reenable it with

    this.refs.btn.removeAttribute("disabled");
    

    Update: the preferred way of handling refs in React is with a function and not a string.

    <button 
      ref={btn => { this.btn = btn; }} 
      onClick={this.onClickUploadFile}
    >Send</button>
    
    
    this.btn.setAttribute("disabled", "disabled");
    this.btn.removeAttribute("disabled");
    

    Update: Using react hooks

    import {useRef} from 'react';
    let btnRef = useRef();
    
    const onBtnClick = e => {
      if(btnRef.current){
        btnRef.current.setAttribute("disabled", "disabled");
      }
    }
    
    <button ref={btnRef} onClick={onBtnClick}>Send</button>
    

    here is a small example using the code you provided https://jsfiddle.net/69z2wepo/30824/

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题