当用户单击注销按钮时,我试图使用SweetAlert作为警报。我就是这么做的。SweetAlert (从它们的回购中复制的示例):
const signOutUser = () => {
return (
<SweetAlert
warning
showCancel
confirmBtnText="Yes, delete it!"
confirmBtnBsStyle="danger"
title="Are you sure?"
onConfirm={() => console.log('hey')}
onCancel={() => console.log('bye')}
focusCancelBtn
>
You will not be able to recover this imaginary file!
</SweetAlert>
)}我就是这么叫它的:
const Border = () => (
...
<a onClick={signOutUser}/>
...
)问题是,当我点击它时,什么也不会发生。有什么想法吗?
发布于 2020-07-22 20:25:50
您的SweetAlert组件需要始终呈现(除特定情况外)。触发SweetAlert的是show支柱,它是一个布尔。
您可以将show支柱绑定到组件的状态。让我给你们举个例子:
export default function YourAlert() {
const [isOpen, setOpen] = useState(false);
return (
<SweetAlert
warning
showCancel
show={isOpen} //Notice how we bind the show property to our component state
confirmBtnText="Yes, delete it!"
confirmBtnBsStyle="danger"
title="Are you sure?"
onConfirm={() => console.log("hey")}
onCancel={() => {
console.log("bye");
setOpen(false); // Don't forget to close the modal
}}
focusCancelBtn
>
You will not be able to recover this imaginary file!
</SweetAlert>
<Button
onClick={()=>{
setOpen(true); // Open the modal
}}
>Open the alert</Button>
);
}注意我评论的地方,因为它会让你理解实现。
发布于 2020-07-22 20:28:28
根据文档的说法,SweetAlert组件有一个表演道具
import React, { Component } from 'react';
import SweetAlert from 'sweetalert-react';
// ...
render() {
return (
<div>
<button onClick={() => this.setState({ show: true })}>Alert</button>
<SweetAlert
show={this.state.show}
title="Demo"
text="SweetAlert in React"
onConfirm={() => this.setState({ show: false })}
/>
</div>
);
}因此,您需要将一个布尔值传递给该道具并切换它。
发布于 2020-07-22 20:34:16
您不能将组件传递给这样的onclick。
阅读有关条件渲染的文档页面。
您可以获得按钮来更新状态变量,然后根据状态变量的值有条件地呈现警报组件。
下面是一个示例(使用红色div,但将其用于SweetAlert):
const SignOutUser = () => (
<div style={{ backgroundColor: "red" }}>
You will not be able to recover this imaginary file!
</div>
);
const App = () => {
const [showAlert, setShowAlert] = React.useState(true)
return (
<div className="App">
<button onClick={() => setShowAlert(false)}>Click Me</button>
{!showAlert && <SignOutUser/>}
</div>
);
}
ReactDOM.render( <App /> , document.getElementById("root"));<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>
https://stackoverflow.com/questions/63042564
复制相似问题