繁体   English   中英

在反应js中单击确认警报后如何在页面中显示消息

[英]how to make display message in page after click confirm alert in react js

在我下面的代码中使用 react js 我想当我点击确认警报 ok 然后它在 web 页面中显示消息成功。在 web 页面中不显示。

我们怎样才能做到这一点有任何帮助。 非常感谢。

任何人请帮我解决这个问题。

请在我的代码中检查我要达到的目标

查看

我真的不明白你想做什么。

您的代码可以显示问题提示。 如果您想摆脱唯一的记录,您可以简单地向您的 class 组件添加一个引用,如下所示:

constructor(props) {
    super(props);
    this.myRef = React.createRef(null);
}

然后添加 function 来处理您的删除逻辑,例如:发出 POST 请求以删除该特定项目。

handleRemoveItem = (e) => {

    const res = window.confirm("Delete the item?");
    /**
     * Probably a POST request to delete 
     * the record with the key 'e'.
     * Or handle múltiples refs.
     */ 
    if (res)
      this.myRef.current.remove();
}

将 ref 添加到按钮,您已经完成了 rest:

<button
  className="btn btn-danger"
  ref={this.myRef}
  onClick={this.handleRemoveItem}
>

如果您想显示错误或成功消息,请将 props 添加到您的组件中,以便在多个用例中重复使用它。 但是,为了让您可视化这种行为,这可能很有用:

{(this.state.error || this.state.success) && (
  <span className="message">
    {this.state.error
      ? this.state.errorMessage
      : this.state.successMessage}
  </span>
)}

将 state 添加到构造函数中:

this.state = {
  error: false,
  success: false,
  errorMessage: 'Your error message!',
  successMessage: 'Your success messsage'
};

最后,处理程序的逻辑:

handleRemoveItem = (e) => {

    const res = window.confirm("Delete the item?");
    /**
     * Probably a POST request to delete 
     * the record with the key 'e'.
     * Or handle múltiples refs.
     */ 
    if (res) {
      this.myRef.current.remove();
      this.setState({ success: true });
      setTimeout(() => this.setState({ success: false }), 3000);
    } else {
      this.setState({ error: true });
      setTimeout(() => this.setState({ error: false }), 3000);
    }
}

代码

您共享的代码沙箱是“记录”消息,而不是显示在屏幕上。 我已经根据用户选择的选项更新了代码以更新 state。

  handleAgree = () => {
    this.setState({ agreedState: "I agree!" });
    this.handleClose();
  };

  handleDisagree = () => {
    this.setState({ agreedState: "I do not agree!" });
    this.handleClose();
  };

最后我们可以显示消息:

{/* Showing message according to the selected option */}
<h1>{this.state.agreedState}</h1>

这是更新的代码沙箱

您可以使用const res = window.confirm("Delete the item?"); 检查单击OKCancel from alert 之后,当用户单击“确定”时,您可以根据需要显示您的消息成功。

https://codesandbox.io/s/eager-haslett-y63ld?file=/src/index.js

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM