How integrate jQuery plugin in React

后端 未结 2 1202
孤街浪徒
孤街浪徒 2021-02-06 11:30

I want to use https://github.com/t1m0n/air-datepicker with in a React app, but it doesn\'t work.

2条回答
  •  忘了有多久
    2021-02-06 11:41

    air-datepicker is not the React-component. It is the jquery-plugin, so we can follow this tutorial https://reactjs.org/docs/integrating-with-other-libraries.html

    import React from 'react'
    import $ from 'jquery'
    import 'air-datepicker/dist/js/datepicker.js'
    import 'air-datepicker/dist/css/datepicker.css'
    
    class AirDatepicker extends React.Component {
        componentDidMount(){
            this.$el = $(this.el)
            this.$el.datepicker()
        }
    
        render() {
            return (
                
    this.el = el}/>
    ) } } export default AirDatepicker

    But it still not work cause the jquery not the dependency of the air-datepicker.

    ReferenceError: jQuery is not defined
    ./node_modules/air-datepicker/dist/js/datepicker.js
    D:/demo/react/jq-plugin/datepicker/node_modules/air-datepicker/dist/js/datepicker.js:2236
      2233 |         }
      2234 |     };
      2235 | })();
    > 2236 |  })(window, jQuery);
      2237 | 
      2238 | 
      2239 | //////////////////
    

    Follow the error message and the easiest way is to hake the air-datepicker. Add jQuery as the dependency in the first line of the air-datepicker/dist/js/datepicker.js

    Before:

      1 |;(function (window, $, undefined) { ;(function () {
      2 |    var VERSION = '2.2.3',
      3 |        pluginName = 'datepicker'
    

    After:

    > 1 |import jQuery from 'jquery'
      2 |;(function (window, $, undefined) { ;(function () {
      3 |    var VERSION = '2.2.3',
      4 |        pluginName = 'datepicker'
    

    Thus can works well as the React-component.

提交回复
热议问题