Javascript 使用带有错误的第三方库
我正在尝试在我的react应用程序中使用第三方插件,如bootstrap tagsinout和noUiSlider。我已通过npm将这些库安装到我的package.json中。目前我正在初始化componentDidMount方法中的插件。我就是这样做的Javascript 使用带有错误的第三方库,javascript,reactjs,twitter-bootstrap-3,nouislider,bootstrap-tags-input,Javascript,Reactjs,Twitter Bootstrap 3,Nouislider,Bootstrap Tags Input,我正在尝试在我的react应用程序中使用第三方插件,如bootstrap tagsinout和noUiSlider。我已通过npm将这些库安装到我的package.json中。目前我正在初始化componentDidMount方法中的插件。我就是这样做的 componentDidMount = () => { $(document).ready(function() { // Apply the plugin to the element
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
}
});
});
这是我给tagsinput的div
<div className="form-group form-group-default">
<label>Tags</label>
<input id="#tagsinput" type="text" value="Smoking,Drinking" data-role="tagsinput"/>
</div>
及
我在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']
}
});
不建议在react组件中使用jQuery,因为react处理虚拟DOM和差异的方式。简而言之,React跟踪DOM中的元素,并在适当的时候添加/删除/更新它们。因此,使用jQuery查找的元素可能还不存在于DOM中。另外,
$(document).ready…
包装程序在安装组件之前不会运行,因此在运行jQuery之前,documentready
事件可能已经触发
您需要研究如何使用React
refs
访问React:中的DOM元素,如facebook示例:
constructor(props) {
super(props);
...
this.myRef = React.createRef();
}
在render()中:
return请查看我的问题中添加的更新。这不起作用:(使用ref时需要将输入附加到组件:ref={(input)=>{this.textInput=input}}
。然后,您可以使用this.textInput
引用DOM节点。请注意,由于原始答案中所述的原因,它不一定会授予您访问jQuery方法的权限。我使用了this.textInput,但它并没有引用textInput变量。当我仅使用textInput时,它开始引用变量。奇怪。但您可以吗告诉我在react中使用此插件的最佳方法?
<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
constructor(props) {
super(props);
...
this.myRef = React.createRef();
}
this.myRef.current.someEvent = this.eventHandler;
this.myRef.current.tagsinput({ ...