在React中使用Flexslider jQuery插件

时间:2019-05-06 03:07:45

标签: jquery reactjs flexslider

我正在尝试使用flexslider,这是React组件内部的jQuery插件。

这是组件:

import React from 'react';
import Testimonial from './testimonial';
import testimonialData from '../API/testimonials.json';
import $ from 'jquery';
import '../flexslider/JS/jquery.flexslider';

class Testimonials extends React.Component {
    divRef;

    componentDidMount() {
        $(this.divRef).flexslider({
            animation: 'slide',
            controlNav: false
        });
    }
    shouldComponentUpdate() {
        return false;
    }

    setRef = (ref) => {
        this.divRef = ref;
    };

    render() {
        return (
            <div className="container mt-5 pt-2">
                <hr className="testimonials_hr" />
                <h1 className="text-center pb-5">Testimonials</h1>
                <div className="flexslider" ref={this.setRef}>
                    <ul class="slides">
                        {testimonialData.map((element) => <Testimonial id={element.id} {...element} />)}
                    </ul>
                </div>
            </div>
        );
    }
}

export default Testimonials;

我已经安装了jQuery,还下载了jQuery.flexslider文件。我已经将其保存在src文件夹中,并将其导入到组件中以使用flexslider()。

当我编译时,它显示在浏览器上:

./src/flexslider/JS/jquery.flexslider.js
  Line 25:  'DocumentTouch' is not defined  no-undef
  Line 199:  'MSGesture' is not defined      no-undef
  Line 521:  'MSGesture' is not defined      no-undef
  Line 1252:  'jQuery' is not defined         no-undef

Search for the keywords to learn more about each error.

我做错了什么?

在使用jQuery插件的React组件中使用Flexslider怎么办?

1 个答案:

答案 0 :(得分:0)

flexslider需要jQuery处于全局范围(例如:window)才能将其功能绑定到jQuery对象。

想到的一种可能的解决方案是要求它们像html文件中的任何普通脚本一样:

<!-- styles -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/flexslider/2.7.2/flexslider.min.css" />

<!-- scripts -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/flexslider/2.7.2/jquery.flexslider-min.js"></script>

<!-- Scripts can also be loaded from local space if available in source directory -->

我发现的另一种解决方案是使用require插件而不是import并在jQuery对象上定义$window

import React from "react";
import $ from 'jquery'; // jQuery import

import 'flexslider/flexslider.css'; // The styles if needed

window.jQuery = window.$ = $;
require('flexslider'); // This uses the NPM-package, but it can be replaced by the local file.