将Sweet Alert弹出窗口添加到React组件中的按钮

Jor*_*son 7 javascript twitter-bootstrap reactjs sweetalert

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

http://djorg83.github.io/react-bootstrap-sweetalert/

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

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

这是删除按钮的组件:

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>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

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

<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>
Run Code Online (Sandbox Code Playgroud)

有人知道怎么做吗?

hin*_*nok 13

基于您的代码的工作示例http://www.webpackbin.com/VJTK2XgQM

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

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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)