簡體   English   中英

如何使用ReactJS在單擊刪除按鈕上創建彈出窗口?

[英]How to create a popup on click delete button with ReactJS?

我想要單擊按鈕刪除時,它會彈出一個確認對話框。 我嘗試使用sweetAlert ,但未顯示任何彈出窗口。

popupdel方法:

 popupdel() {
    swal({
      title: "Are you sure?",
      text: "Your will not be able to recover this imaginary file!",
      type: "warning",
      showCancelButton: true,
      confirmButtonClass: "btn-danger",
      confirmButtonText: "Yes, delete it!",
      closeOnConfirm: false
    }, function() {
      swal("Deleted!", "Your imaginary file has been deleted.", "success");
    });
  }

刪除方法:

delete(Code) {

axios.delete('http://localhost:4000/app/deleteclient/' + Code).then(function(clients) {

this.setState({ clients: clients.records });

}.bind(this));

}

<button style={btn} onClick={(Code) => this.delete(client.Code)} type="button"><i class="fa fa-trash-o"></i></button>

如何使彈出窗口顯示在單擊按鈕上?

就在上周,我為SweetAlert2創建了自己的React包裝器組件。 (NPM上已經有一些包裝器類,但是我不喜歡它們的工作方式,所以我制作了自己的包裝器。)以下鏈接是這兩個功能齊全的示例:A)我的SweetAlert2的包裝器組件,以及B)基於用戶輸入啟動警報的兩種不同方式。

https://stackblitz.com/edit/react-sweetalert2-wrapper

鏈接的示例顯示了如何聲明式啟動警報(例如,在render()函數中拼出JSX代碼,然后切換狀態中的show變量)或強制性地(例如,在render()為警報留一個占位符render()函數,該函數將使用null或新生成的警報的內容動態填充)。

如果我了解您要實現的目標:

  1. 您可以為正在顯示或不顯示的彈出窗口創建某種狀態。 這將是一個布爾值。
  2. 將初始狀態設置為false。
  3. 創建一個方法,當您單擊按鈕時,它將狀態切換為true。
  4. 狀態為true時,顯示彈出窗口。

然后根據您的應用程序結構將方法傳遞給您的按鈕。

class Example extends React.Component {
  constructor() {
      super();
      this.state = {
          isPopupShown: false
      }

     this.togglePopup = this.togglePopup.bind(this);
  }


  togglePopup() {
    this.setState(prevState => ({
      isPopupShown: !prevState.isPopupShown
    }));
  }

  render() {
    return (
      <div>
        <button onClick={ this.togglePopup }>
          toggle popup
        </button>
        { this.state.isPopupShown === true ? <div>popup shown!</div> : <div>popup hidden!</div> }
      </div>
    )
  }
}

ReactDOM.render(<Example />, document.querySelector("#app"))

這是一個顯示如何切換內容的jsfiddle: http : //jsfiddle.net/n5u2wwjg/100862/

使用確認而不是警報或sweetAlert:

delete(Code) {
    if( confirm('Sure want to delete?')) {
        axios.delete('http://localhost:4000/app/deleteclient/' + Code).then(function(clients) {

    this.setState({ clients: clients.records });
)}

else {
        // Do something..
    } }.bind(this));

    <button style={btn} onClick={(Code) => this.delete(client.Code)} type="button"><i class="fa fa-trash-o"></i></button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM