gpt4 book ai didi

reactjs - 如何在 React.js 中显示 Bootstrap 5 Toast?

转载 作者:行者123 更新时间:2023-12-04 14:56:09 26 4
gpt4 key购买 nike

按照以下方法显示 Bootstrap 5 Toast单击 React.js 中的按钮动态
进口声明:

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 不显示。

最佳答案

您可以使用 useRefuseEffect react 钩子(Hook)...

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

关于reactjs - 如何在 React.js 中显示 Bootstrap 5 Toast?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67946016/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com