【问题标题】:How to disable a button after clicking?单击后如何禁用按钮?
【发布时间】:2019-10-25 10:24:54
【问题描述】:

我正在通过文本字段保存一个值,在单击按钮后,我想禁用该按钮,以便用户无法再次按下它。

我正在使用 React.js 来实现应用程序。

<button type="button" className="btn btn-info round btn-glow px-2 float-right">Confirm</button>

【问题讨论】:

  • 你需要一个点击事件的处理函数,以及一个保存当前状态的变量,见stackoverflow.com/a/49642037/4504053
  • 请向我们展示您尝试过的一些代码。
  • 您应该使用表单并查找表单的onSubmit 事件而不是按钮的onClick。您知道人们也可以按 Enter 键提交。

标签: html reactjs


【解决方案1】:

创建这样的状态

state = {
    btnIsDisable: false
}

在按钮中设置

<button disabled={this.state.btnIsDisable} type="button" className="btn btn-info round btn-glow px-2 float-right">Confirm</button>

在 onClick 处理程序中改变状态

this.setState({btnIsDisable:true});

【讨论】:

    【解决方案2】:

    您必须创建一个类组件并将初始状态按钮状态设置为true,然后在触发点击功能时将其更改为false

    // Initial state
    this.state = {
        buttonEnabled : true
    };
    
    
    // onClick function
    onClick(event){
        this.setState({buttonEnabled: false});   
    }
    
       render() {
         const { buttonEnabled } = this.state;
        return (
          <div>
            <button onClick={this.onClick} disabled={buttonEnabled}>
              Your content here
            <button>
          </div>
        )
      }
    

    【讨论】:

      【解决方案3】:
      // declare some variable for holding your button's state
      state = {
        disabled: false
      }
      
      ...
      
      onConfirmButtonClick () => {
        // set state.disabled as true
        this.setState({ disabled: true })
      }
      
      
      render () {
        return (
      
          ...
      
          <button
            disabled={this.state.disabled} // add disabled attribute to your button along with your state
            type="button"
            className="btn btn-info round btn-glow px-2 float-right"
          >
            Confirm
          </button>
        )
      }
      

      【讨论】:

        【解决方案4】:

        链接中的工作代码:https://codepen.io/stanlee94/pen/gNOLxb

        class Button extends React.Component {
          state = {
            disabled: false,
            pointerStyle: 'pointer'
          }
        
          handleClick = () => {
            //Do your logic here
            console.log('Record added');
            this.setState({
              disabled: true,
              pointerStyle: 'no-drop'
            });
          }
        
          render() {
            return(
            <button disabled={this.state.disabled} type="button" onClick={this.handleClick}
              style={{ cursor: this.state.pointerStyle }}>Confirm</button>
            );
          }
        }
        

        它会在您点击后添加一个无效类型的指针,为您的用户提供良好的用户体验。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-05-25
          • 1970-01-01
          • 1970-01-01
          • 2011-01-20
          相关资源
          最近更新 更多