React Alert 组件关闭按钮自关闭

新手上路,请多包涵

我有一个使用引导程序类的警报反应组件。

这是组件代码:

 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;

它工作正常,但我的问题是……

单击其中的关闭按钮时,如何使警报自动隐藏?

原文由 user7801216 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 404
2 个回答

您可以在内部使用状态进行操作:

 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;

原文由 Shota 发布,翻译遵循 CC BY-SA 4.0 许可协议

我根据 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;

原文由 blackbull77 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题