出现“类型错误……$(...).modal不是一个函数”的问题

3

我正在尝试创建和编辑函数来更新用户的笔记(在一个REACT项目中),使用Bootstrap模态框,但是这里出现了错误。

Uncaught (in promise) TypeError: jquery__WEBPACK_IMPORTED_MODULE_1___default()(...).modal is not a function
updateNote Notes.js:16
onClick NoteItem.js:15
React 23
js index.js:6
factory react refresh:6
Webpack 3
    __webpack_require__
    <anonymous>
    <anonymous>

我尝试着在论坛上学习有关引入jQuery库和Bootstrap的顺序,但是没有成功。
这是我的代码:
    import React,{ useContext,useEffect,useRef } from "react";
import $ from 'jquery'
import 'bootstrap';
import noteContext from "../context/notes/NoteContext"
import AddNote from "./AddNote";
import NoteItem from "./NoteItem";

export const Notes=() => {
    const context=useContext(noteContext)
    const { notes,getNotes }=context
    useEffect(() => {
        getNotes()
        // eslint-disable-next-line
    },[])
    const ref=useRef(null)
    const updateNote=async (note) => {
        console.log("working")
        $(ref).modal('toggle')
    }
    return (
        <>
            <AddNote />
            <button ref={ref} type="button" className="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
                Launch demo modal
            </button>

            <div className="modal fade" id="exampleModal" tabIndex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
                <div className="modal-dialog" role="document">
                    <div className="modal-content">
                        <div className="modal-header">
                            <h5 className="modal-title" id="exampleModalLabel">Edit Note</h5>
                            <button type="button" className="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div className="modal-body">
                            ...
                        </div>
                        <div className="modal-footer">
                            <button type="button" className="btn btn-secondary" data-dismiss="modal">Close</button>
                            <button type="button" className="btn btn-primary">Save changes</button>
                        </div>
                    </div>
                </div>
            </div>
            <div className="row my-3">
                <h1>Your Notes</h1>
                {notes.map((note) => {
                    return <NoteItem key={note._id} updateNote={updateNote} note={note} />
                })}
            </div>
        </>
    )
}

这是我的index.html文件(我去掉了jquery链接,因为它无法工作):
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="theme-color" content="#000000" />
  <meta name="description" content="Web site created using create-react-app" />
  <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
  <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
  <title>iNotebook - Your notes on the cloud</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
</head>

<body>
  <noscript>You need to enable JavaScript to run this app.</noscript>
  <div id="root">
    <script src="https://kit.fontawesome.com/ae578fcfec.js" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa"
      crossorigin="anonymous"></script>
  </div>
</body>

</html>

我错过了什么吗?

我发现另一篇帖子有类似的问题(React错误:__WEBPACK_IMPORTED_MODULE_4_jquery___default(...)(...)。modal不是一个函数),导入bootstrap也没有起作用,因为它与我安装的@popperjs/core存在依赖关系,但随后出现更多错误:

Module not found: Error: Can't resolve './modifiers/index.js' in '/home/alien/codes/webDev/react/inotebook/node_modules/@popperjs/core/lib'
[0] ERROR in ./node_modules/@popperjs/core/lib/index.js 2:0-37
[0] Module not found: Error: Can't resolve './modifiers/index.js' in '/home/alien/codes/webDev/react/inotebook/node_modules/@popperjs/core/lib'
[0] 
[0] ERROR in ./node_modules/@popperjs/core/lib/popper.js 20:0-37
[0] Module not found: Error: Can't resolve './modifiers/index.js' in '/home/alien/codes/webDev/react/inotebook/node_modules/@popperjs/core/lib'
[0] 
[0] webpack compiled with 2 errors

那么我没有找到任何解决方法,如果这种方法相关或者需要添加什么内容,请告诉我。

为了更好地理解,这是我正在遵循的教程:https://youtu.be/J5hGX5_XZDk。它很旧了,新版本中可能有语法更新,我不确定,所以如果有什么需要改变的,请告诉我。在你提问之前,我一开始按照每个单词跟随这个教程,但后来我不得不查看官方的Bootstrap文档以消除一些错误,这是否还需要改变其他内容呢?

更新后的代码:

import React,{ useContext,useEffect,useRef } from "react";
import noteContext from "../context/notes/NoteContext"
import AddNote from "./AddNote";
import NoteItem from "./NoteItem";

export const Notes=() => {
    const context=useContext(noteContext)
    const { notes,getNotes }=context
    useEffect(() => {
        getNotes()
        // eslint-disable-next-line
    },[])
    const ref=useRef(null)
    const updateNote=async (note) => {
        console.log("working")
        ref.current.click()
    }
    return (
        <>
            <AddNote />
            <button ref={ref} type="button" className="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
                Launch demo modal
            </button>

            <div className="modal fade" id="exampleModal" tabIndex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
                <div className="modal-dialog" role="document">
                    <div className="modal-content">
                        <div className="modal-header">
                            <h5 className="modal-title" id="exampleModalLabel">Edit Note</h5>
                            <button type="button" className="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div className="modal-body">
                            ...
                        </div>
                        <div className="modal-footer">
                            <button type="button" className="btn btn-secondary" data-dismiss="modal">Close</button>
                            <button type="button" className="btn btn-primary">Save changes</button>
                        </div>
                    </div>
                </div>
            </div>
            <div className="row my-3">
                <h1>Your Notes</h1>
                {notes.map((note) => {
                    return <NoteItem key={note._id} updateNote={updateNote} note={note} />
                })}
            </div>
        </>
    )
}

这个回答解决了你的问题吗?TypeError: $(...).modal is not a function with bootstrap Modal - filipe
不,那里的解决方案对错误没有影响。 - kashish patel
1个回答

2

Bootstrap V5有许多重大变化,其中之一是删除了jquery。

这是bootstrap 5如何使用javascript切换模态框的方法。

var myModal = new bootstrap.Modal(document.getElementById('myModal'), {
  keyboard: false
});

myModal.toggle();

您还可以使用数据属性来显示/隐藏模态框。但这与Bootstrap 4中所做的不同。他们已将属性命名空间化data-bs-*(从data-*

在此处查看文档:https://getbootstrap.com/docs/5.0/components/modal/#live-demo

您的代码使用data-toggle="modal" data-target="#exampleModal",但示例显示data-bs-toggle="modal" data-bs-target="#exampleModal"

此外,data-dismiss变成了data-bs-dismiss


通常情况下,使用React和jQuery混合编程被认为是一个不好的选择,不是吗? - Vladislav Ladicky
当然可以。jQuery主要帮助我们度过IE时代。许多主要库都依赖于它。如果你使用的是BootStrap v4.0,那么你别无选择。这是一个依赖项。 - naveen
谢谢你指出这个问题(我看的是旧文档,哈哈),我做了适当的更改并在帖子中更新了新代码,但它只显示ref.toggle不是一个函数,我也尝试了ref.current.toggle,它显示相同的东西,所以我又重新按照教程操作了一遍,但什么都没有发生(我已经在帖子中更新了它)。这里出了什么问题?因为console.log显示该函数正在运行。 - kashish patel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接