如何渲染 SweetAlert React

How to render SweetAlert React

我正在尝试使用 SweetAlert 作为用户单击注销按钮时的提醒。我就是这样做的。 SweetAlert(从他们的 repo 复制的示例):

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}/>
    ...
)

问题是当我点击它时没有任何反应。有什么想法吗?

您的 SweetAlert 组件需要始终呈现(特定情况除外)。触发 SweetAlert 的是 show 属性,它是一个 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>
  );
}

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

根据 documentation SweetAlert 组件有一个 show prop

    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>
  );
}

因此您需要将布尔值传递给该道具并切换它

你不能像那样将组件传递给 onclick。

阅读有关 Conditional Rendering 的文档页面。

您可以获得更新状态变量的按钮,然后根据该状态变量的值有条件地呈现警报组件。

这是一个示例(使用红色 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>