reactjs - 如何在 React.js 中显示 Bootstrap 5 Toast?
问题描述
按照以下方法在 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 不显示。
解决方案
你可以使用useRef
和useEffect
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>
)
}
推荐阅读
- eclipse - AndroidDriver 类型不是通用的;它不能用参数参数化
- css - 带有切换按钮的 Wordpress Divi Blurbs
- c# - NullReferenceException:从附加到游戏对象的脚本访问方法时,对象引用未设置为对象错误的实例
- azure - 如何在 Azure AD 加入设备上的任务计划程序中选择用户
- javascript - POST formdata 到 web api 控制器总是返回模型状态错误
- angular - 在 ng-bootstrap (Angular 2+) 中保存弹出表单内容
- node.js - 如何将 express.static() 与基于 URL 的目录路径一起使用?
- javascript - React setState()不适用于无线电字段handleInput方法
- javascript - Firestore 导出 Cron 作业未运行:错误代码 204
- azure - 错误:C:\Program Files\IIS\Microsoft Web Deploy V3\msdeploy.exe 失败,返回码:4294967295