简体   繁体   中英

React and turn.js (turn is not a function)

I want to run turn.js with react. I found an example here: https://codesandbox.io/s/005xlk45mn

I adapted the code to my project, but i get the following error: TypeError: jquery__WEBPACK_IMPORTED_MODULE_6___default(...)(...).turn is not a function

import React, { Component } from 'react';
import $ from "jquery";
import "turn.js";

const options = {
  width: 800,
  height: 600,
  autoCenter: true,
  display: "double",
  acceleration: true,
  elevation: 50,
  gradients: !$.isTouch,
  when: {
    turned: function(e, page) {
      console.log("Current view: ", $(this).turn("view"));
    }
  }
};

class xxx extends Component {

    constructor(props) {
        super(props);
    }

    componentDidMount() {
        $("#flipbook").turn(options);
    }

    render() {
        return (
                <div id="flipbook">
                    <div className="hard">Turn.js</div>
                    <div className="hard"></div>
                    <div> Page 1 </div>
                    <div> Page 2 </div>
                    <div className="hard"></div>
                    <div className="hard"></div>
                </div>
        );
    }
}

export default Condolences;

this also didnt work:

import * as $ from "jquery"
componentDidMount() {
        $(this.el).turn();
    }
render() {
        return (
                <div id="flipbook" ref={ el => this.el = el }>
                    <div className="hard">Turn.js</div>
                    <div className="hard"></div>
                    <div> Page 1 </div>
                    <div> Page 2 </div>
                    <div className="hard"></div>
                    <div className="hard"></div>
                </div>
        );
    }

It looks like the turn.js plugin is not being attached to your instance of jQuery. This is likely related to your webpack setup. As you noted, the code works fine in codesandbox.

In order to install itself as a jQuery plugin, turn.js needs to modify a global jQuery object. Try using ProvidePlugin in your webpack config so that jQuery is exposed to turn.js. Perhaps something like this:

new webpack.ProvidePlugin({
    'window.jQuery': 'jquery',
    'window.$': 'jquery',
    $: 'jquery'
})

I had the same problem... and I solved using a lower version of jQuery like the npm description says

Latest version uses jQuery 1.12.0 because jQuery 3.x was breaking the page flipper.

use JQuery version 1.12.0 and it works

I even made a demo using React 16.10.x

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM