gpt4 book ai didi

ReactJS - onClick SweetAlert 不工作

转载 作者:行者123 更新时间:2023-12-05 06:30:13 28 4
gpt4 key购买 nike

我正在使用 ReactJS(和 nodejs、mongodb..),我有一个带有删除选项的项目,我想显示一个删除警报确认窗口,这是我第一次使用 SweetAlert。它显示 SweetAlert 但不让我选择选项,立即删除项目。我会展示一个 gif,这样你就可以看到发生了什么。

谢谢!

我的项目页面组件:

import React, { Component } from 'react';
import { NavLink } from 'react-router-dom';
import moment from 'moment';

import SweetAlert from 'react-bootstrap-sweetalert'
import Tasks from '../../TaskList/Tasks/Tasks';

import './ProjectPage.css';



class ProjectPage extends Component {
constructor(props) {
super(props);
this.state = {
project: {},
alert: null
};
}

componentDidMount() {

const { match: { params } } = this.props;

fetch(`/dashboard/project/${params.id}`)
.then(response => {
return response.json()
}).then(project => {
this.setState({
project: project
})
})
}

deleteProject(e){
const getAlert = () => (
<SweetAlert
warning
showCancel
confirmBtnText="Yes!"
confirmBtnBsStyle="danger"
cancelBtnBsStyle="default"
title="Are you sure you want to delete this project?"
onConfirm={() => this.deleteFile()}
onCancel={() => this.onCancelDelete()}
>
You will not be able to recover this project!
</SweetAlert>
);
this.setState({
alert: getAlert()
});

e.preventDefault();
}

onCancelDelete(){
this.setState({
alert: null
});
}

render() {

const { match: { params } } = this.props;

const BackgroundImage = {
backgroundImage: `url(${this.state.project.imageURL})`,
backgroundRepeat: 'no-repeat',
backgroundSize: 'cover',
backgroundPosition: 'center',
height: '350px',
opacity: '0.7'
}
return (

<div>
<header style={BackgroundImage}>
[...]
<form method='POST' action={`/dashboard/project/${params.id}/delete?_method=DELETE`}>

<button id='button__project-delete' style={{ boxShadow: 'none' }} className='button__options--project btn btn-outline-secondary'
type='submit' onClick={() => this.deleteProject()}>Delete</button> {this.state.alert}

</form>

</header>
[...]
</div>

);
}
}
export default ProjectPage;

GIF 发生了什么:

enter image description here

最佳答案

看起来你的页面在按钮点击时刷新了,因为它在一个表单对象中。单击按钮时,无法访问单击事件。所以 e.preventDefault() 不起作用。

您必须将事件对象传递给deleteProject() 方法。改变这一行

<button id='button__project-delete' style={{ boxShadow: 'none' }} className='button__options--project btn btn-outline-secondary' 
type='submit' onClick={() => this.deleteProject()}>Delete</button> {this.state.alert}

<button id='button__project-delete' style={{ boxShadow: 'none' }} className='button__options--project btn btn-outline-secondary' 
type='submit' onClick={(e) => this.deleteProject(e)}>Delete</button> {this.state.alert}

关于ReactJS - onClick SweetAlert 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52738041/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com