本文介绍了将Sweet Alert弹出窗口添加到React组件中的按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为Bootstrap和React(我在Meteor应用程序中使用)找到了这个完美的Sweet Alert模块:

I found this perfect Sweet Alert module for Bootstrap and React (which I'm using in my Meteor app):

但我不明白你如何在React组件中包含这些代码。

But I don't understand how you include this code inside a React component.

当有人点击我的应用程序中的删除按钮时,我想要一个Sweet Alert提示弹出要求确认。

When someone clicks the Delete button in my app, I'd like a Sweet Alert prompt to pop up asking for confirmation.

这是删除按钮的组件:

import React, {Component} from 'react';
import Goals from '/imports/collections/goals/goals.js'
import SweetAlert from 'react-bootstrap-sweetalert';

export default class DeleteGoalButton extends Component {

  deleteThisGoal(){
    console.log('Goal deleted!');
    // Meteor.call('goals.remove', this.props.goalId);
  }

  render(){
    return(
      <div className="inline">
          <a onClick={this.deleteThisGoal()} href={`/students/${this.props.studentId}/}`}
          className='btn btn-danger'><i className="fa fa-trash" aria-hidden="true"></i> Delete Goal</a>
      </div>
    )
  }
}

以下是我从Sweet Alert示例中复制的代码:

And here is the code that I copied from the Sweet Alert example:

<SweetAlert
    warning
    showCancel
    confirmBtnText="Yes, delete it!"
    confirmBtnBsStyle="danger"
    cancelBtnBsStyle="default"
    title="Are you sure?"
    onConfirm={this.deleteFile}
    onCancel={this.cancelDelete}
>
    You will not be able to recover this imaginary file!
</SweetAlert>

任何人都知道怎么做?

推荐答案

基于您的代码的工作示例

Working example based on your code http://www.webpackbin.com/VJTK2XgQM

你应该使用 this.setState()并创建< ; SweetAlert ... /> on onClick 。您可以使用胖箭头或 .bind()或任何其他方法来确保使用正确的上下文。

You should use this.setState() and create <SweetAlert ... /> on onClick. You can use fat arrows or .bind() or any other method to be sure that proper context is used.

import React, {Component} from 'react';
import SweetAlert from 'react-bootstrap-sweetalert';

export default class HelloWorld extends Component {

  constructor(props) {
    super(props);

    this.state = {
      alert: null
    };
  } 

  deleteThisGoal() {
    const getAlert = () => (
      <SweetAlert 
        success 
        title="Woot!" 
        onConfirm={() => this.hideAlert()}
      >
        Hello world!
      </SweetAlert>
    );

    this.setState({
      alert: getAlert()
    });
  }

  hideAlert() {
    console.log('Hiding alert...');
    this.setState({
      alert: null
    });
  }

  render() {
    return (
      <div style={{ padding: '20px' }}>
          <a 
            onClick={() => this.deleteThisGoal()}
            className='btn btn-danger'
          >
            <i className="fa fa-trash" aria-hidden="true"></i> Delete Goal
        </a>
        {this.state.alert}
      </div>
    );
  }
}

这篇关于将Sweet Alert弹出窗口添加到React组件中的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 10:35