【问题标题】:How to show Bootstrap 5 Toast in React.js?如何在 React.js 中显示 Bootstrap 5 Toast?
【发布时间】:2021-08-28 22:18:09
【问题描述】:

按照以下方法在 React.js 中单击按钮时动态显示 Bootstrap 5 Toast

进口声明:

import * as bootstrap from 'bootstrap';

按钮点击提交处理程序:

let toastEl = document.getElementById('myToast');
let toast = new bootstrap.Toast(toastEl, {autohide: false});
toast.show();

渲染:

<div class="toast align-items-center" id="myToast" role="alert" aria-live="assertive" aria-atomic="true">
  <div class="d-flex">
    <div class="toast-body">
    Hello, world! This is a toast message.
  </div>
    <button type="button" class="btn-close me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
  </div>
</div>

<button type="button" className="btn btn-primary" id="showToast" onClick={this.showToast}>Show Toast</button>

是否有任何替代方法可以以 React 方式执行此操作,因为不建议在 React 中使用 document.getElementById? 尝试使用 Ref,但 Toast 不显示。

【问题讨论】:

  • @ShivamJha react-bootstrap 仍在使用 Bootstrap 4。我正在尝试使用普通的 Bootstrap 5。
  • 所以检查this
  • @ShivamJha 该示例未显示 javascript 代码

标签: reactjs bootstrap-5 bootstrap-toast


【解决方案1】:

您可以使用 useRefuseEffect React 钩子...

const { useState, useEffect, useRef } = React
const { Toast } = bootstrap


function ToastDemo() {
    var [toast, setToast] = useState(false);
    const toastRef = useRef();

    useEffect(() => {
        var myToast = toastRef.current
        var bsToast = bootstrap.Toast.getInstance(myToast)
        
        if (!bsToast) {
            // initialize Toast
            bsToast = new Toast(myToast, {autohide: false})
            // hide after init
            bsToast.hide()
            setToast(false)
        }
        else {
            // toggle
            toast ? bsToast.show() : bsToast.hide()
        }
    })

    return (
    <div className="py-2">
        <button className="btn btn-success" onClick={() => setToast(toast => !toast)}>
            Toast {toast?'hide':'show'}
        </button>
        <div className="toast position-absolute m-4" role="alert" ref={toastRef}>
            <div className="toast-body">
              Hello, world! This is a toast message.
            </div>
        </div>
    </div>
    )
}

Bootstrap 5 with React demos

【讨论】:

    猜你喜欢
    • 2019-06-29
    • 2021-04-04
    • 1970-01-01
    • 2014-12-01
    • 2011-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    相关资源
    最近更新 更多