我正在尝试在我的 React 应用程序中使用第三方插件,例如 bootstrap-tagsinout 和 noUiSlider。我已通过 npm 将库安装到我的 package.json 中。目前我正在我的 componentDidMount 方法中初始化插件。我就是这样做的
componentDidMount = () => {
$(document).ready(function() {
// Apply the plugin to the element
$("#ionSlider-newTag").ionRangeSlider({
min: 0,
max: 5000,
type: 'double',
postfix: 's',
maxPostfix: "+",
prettify: false,
hasGrid: true,
from: 1600,
to: 2950
});
});
$(document).ready(function() {
$('#tagsinput').tagsinput({
typeahead: {
source: ['Smoking, Drinking, Eating']
}
});
});
$(document).ready(function() {
// Apply the plugin to the element
$("#noUiSlider").noUiSlider({
start: 40,
connect: "lower",
range: {
'min': 0,
'max': 100
}
});
});
这是我的标签输入 div
<div className="form-group form-group-default">
<label>Tags</label>
<input id="#tagsinput" type="text" value="Smoking,Drinking" data-role="tagsinput"/>
</div>
当我运行它时,我收到一条错误消息
index.js:121 Uncaught TypeError: $(...).tagsinput is not a function
和
index.js:121 Uncaught TypeError: $(...).noUiSlider is not a function
我在我的 react 组件中导入了插件
import 'ion-rangeslider'
import 'bootstrap-tagsinput'
import 'nouislider'
import $ from 'jquery'
我已经查找了所有已经存在的问题并尝试了它们。但没有任何效果。我做错了什么?
更新
我尝试使用引用文献,但没有帮助
<input id="#tagsinput" type="text" ref={(input) => {textInput = input; }} value="Smoking,Drinking" data-role="tagsinput"/>
textInput.tagsinput({
typeahead: {
source: ['Smoking, Drinking, Eating']
}
});
但我收到此错误
Uncaught TypeError: Cannot read property 'tagsinput' of undefined
最佳答案
不建议在 React 组件中使用 jQuery,因为 React 处理虚拟 DOM 和比较的方式。简而言之,React 跟踪 DOM 中的元素,并在适当且高性能时添加/删除/更新它们。因此,您使用 jQuery 查找的元素可能还不存在于 DOM 中。此外,在安装组件之前,$(document).ready...
包装器不会运行,因此文档 ready
事件可能在 jQuery 运行之前触发。
您需要研究使用 React refs
来访问 React 中的 DOM 元素:https://facebook.github.io/react/docs/refs-and-the-dom.html
关于javascript - 使用第三方库和 React js 出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44325282/