单击后如何禁用按钮?

时间:2019-06-11 03:50:09

标签: html reactjs

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

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

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

4 个答案:

答案 0 :(得分: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});

答案 1 :(得分:0)

您必须创建一个类组件,并将初始状态按钮的状态设置为true,然后在触发click函数时将其更改为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>
    )
  }

答案 2 :(得分:0)

// 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>
  )
}

答案 3 :(得分:0)

链接中的工作代码: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>
    );
  }
}

单击后,它将添加无效的指针类型,以为用户提供良好的用户体验。

相关问题