网站搜索

javascript - React 警告组件关闭按钮自我关闭


我有一个使用 Bootstrap 类的 alert React 组件。

这是组件代码:

import React, { Component } from 'react';

class Alert extends Component {
  render() {
    return (
      <div>
        <div className="alert alert-warning alert-dismissible" role="alert">
          <button type="button" className="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
          {this.props.text}
        </div>
      </div>
    );
  }
}

export default Alert;

它运行良好,但我的问题是……

我如何在点击警报中的关闭按钮时让警报自动隐藏?

答案#1

你可以在内部使用状态来完成它:

import React, { Component } from 'react';

class Alert extends Component {

  constructor(props, context) {
    super(props, context);
    this.state = {
      isActive: true,
    }
  }

  hideAlert() {
    this.setState({
      isActive: false,
    });
  }

  render() {
    if (this.state.isActive) {
      return (
          <div
            className="alert alert-warning alert-dismissible"
            role="alert"
          >
            <button
              type="button"
              className="close"
              data-dismiss="alert"
              aria-label="Close"
              onClick={() => this.hideAlert()}
            >
              <span aria-hidden="true">&times;</span>
            </button>
            {this.props.text}
          </div>
      );
    }
    return <div/>
  }
}

export default Alert;

答案#2

我根据d.lime的建议更新了AppsWithHeart的代码。如果有更简短(或更简单)的方法来写这个 if 语句,请留言。

import React from "react";

function Alert() {
  const [showPopup, setShowPopup] = React.useState(false);

  const toggleShowInfoPopup = () => {
    setShowPopup(!showPopup);
  };

  return (
    <>
      {(() => {
        if (!showPopup) {
          return (
            <div className="alert alert-warning alert-dismissible" role="alert">
              <button
                type="button"
                className="close"
                data-dismiss="alert"
                aria-label="Close"
                onClick={toggleShowInfoPopup}
              >
                <span aria-hidden="true">&times;</span>
              </button>
              Test
            </div>
          );
        }
      })()}
    </>
  );
}

export default Alert;