首页 > 解决方案 > 如何渲染 SweetAlert React

问题描述

当用户单击注销按钮时,我正在尝试使用 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}/>
    ...
)

问题是当我点击它时,什么也没有发生。有任何想法吗?

标签: reactjssweetalert

解决方案


您的SweetAlert组件需要始终呈现(特定情况除外)。触发 SweetAlert 的是showprop,它是一个Boolean

您可以将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>
  );
}

注意我评论的地方,因为它会让你理解实现。


推荐阅读