发布于 2026-01-06 4 阅读
0

如何在 React 中使用 Bootstrap 5?

将 Bootstrap 5 与 React 结合使用

如何在 React 中使用 Bootstrap 5

如何在 React 中使用 Bootstrap 5

Bootstrap 和 React 都已经存在一段时间了,但现在Bootstrap 5 beta 版发布了,终于有值得庆祝的事情了!🙌

现在 Bootstrap 5 不再需要 jQuery,在 React 应用中使用它变得更加容易,而且不会出现冲突!😲 由于 Bootstrap 5 组件现在以原生 JS 插件的形式编写,因此可以更好地与 React 的最佳实践保持一致。

这也意味着可以使用 Bootstrap 5 组件,而无需像 react-bootstrap 或 reactstrap 这样的第三方库。


首先,将 Bootstrap 添加到你的 React 应用中package.json

npm install bootstrap --save

一旦引入 Bootstrap,你就可以import像使用任何 JS 模块一样使用组件。例如,让我们导入 Bootstrap 的 Toast 组件……

import { Toast} from bootstrap

然后将其与 React 的useEffecthooksuseState一起使用……

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" role="alert" ref={toastRef}>
            <div className="toast-header">
                <strong className="me-auto">Bootstrap 5</strong>
                <small>4 mins ago</small>
                <button type="button" className="btn-close" onClick={() => setToast(false)} aria-label="Close"></button>
            </div>
            <div className="toast-body">
              Hello, world! This is a toast message.
            </div>
        </div>
    </div>
    )
}
Enter fullscreen mode Exit fullscreen mode

或者,(如果这还不够简单的话)data-bs-直接在标记中使用新的命名空间属性。例如,我们来使用 Bootstrap 5 的 Collapse 组件……

function CollapseDemo() {
  return (
    <div className="py-2">
        <button className="btn btn-primary" data-bs-target="#collapseTarget" data-bs-toggle="collapse">
            Toggle collapse
        </button>
        <div className="collapse" id="collapseTarget">
            This is the toggle-able content!
        </div>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

现在,您可以轻松地在 React 项目中使用任何Bootstrap 5 组件。不妨看看这些使用 Bootstrap 5 Toast、Alert、Collapse、Modal、Tooltip 和 Popover 的 React 示例。此外,也请务必了解Bootstrap 5 的所有新更新

您怎么看?您计划在下一个 React 项目中使用 Bootstrap 5 吗?还是您更喜欢其他对 React 友好的设计系统?

文章来源:https://dev.to/codeply/is-bootstrap-5-react-worthy-4493