【问题标题】:Change button text after popUp whit React and sweetalert2-react使用 React 和 sweetalert2-react 在弹出后更改按钮文本
【发布时间】:2018-10-31 13:38:39
【问题描述】:

我正在学习反应,我试图在 sweetAlert2-react 弹出后更改我的按钮文本。 按钮上的原始文本是 'ACTIVE' 和 如果我在弹出窗口中选择“确定”,则必须“激活”按钮上的文本,如果选择“取消”“已禁用”..

我不知道如何或在哪里进行 IF 迭代 有什么帮助吗?

这是我的代码:

<button onClick={() => this.setState({ show: true })}>ACTIVE</button> <SweetAlert show={this.state.show} showCancelButton={this.state.show} title="Are you shore?" onConfirm={() => this.setState({ show: false })} />

谢谢!

【问题讨论】:

    标签: javascript reactjs sweetalert2


    【解决方案1】:

    有条件地设置按钮内部的字符串。

    <button>
        {this.state.active === 'active' && <div>ok</div>}
        {this.state.active === 'disabled' && <div>idk</div>}
    <button>
    

    如果只有两种状态,请考虑使用三元运算符。

    <button>
        {this.state.active === 'active' ? <div>ok</div> : <div>idk</div>}
    <button>
    

    【讨论】:

      【解决方案2】:

      您可以将按钮的文本保存在状态中,(例如:this.state.buttonText),然后您就可以在用户单击OK/Cancel 按钮时设置buttonText

      您可以使用通用方法(在下面的示例中为hideAlert)来管理两个事件(确定和取消)并在其中设置按钮的文本。

      请看下面的例子 (click here to run):

      import React, { Component } from "react";
      import SweetAlert from "react-bootstrap-sweetalert";
      import ReactDOM from "react-dom";
      
      export default class HelloWorld extends Component {
        constructor(props) {
          super(props);
      
          this.state = {
            alert: null,
            button: "active"
          };
        }
      
        showAlert() {
          const getAlert = () => (
            <SweetAlert
              show={this.state.show}
              showCancel
              onConfirm={() => this.hideAlert("disabled")}
              onCancel={() => this.hideAlert("active")}
            >
              Are you sure?
            </SweetAlert>
          );
      
          this.setState({
            alert: getAlert()
          });
        }
      
        hideAlert(text) {
          this.setState({
            alert: null,
            button: text
          });
        }
      
        render() {
          return (
            <div style={{ padding: "20px" }}>
              <button onClick={() => this.showAlert()}>
                {this.state.button}
              </button>
              {this.state.alert}
            </div>
          );
        }
      }
      
      ReactDOM.render(<HelloWorld />, document.getElementById("app"));
      

      希望对你有帮助,再见。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-05-23
        • 1970-01-01
        • 2018-04-14
        • 2017-06-10
        • 2018-08-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多