从ReactJS调用Javascript引发窗口引用错误

时间:2019-01-29 22:30:20

标签: javascript reactjs

我正在研究ReactJS代码,在其中调用Javascript代码以实现一些概念。

我已经将我的Javascript文件(MyJavascript.js)包含在ReactJS项目中。 当我使用npm run dev运行ReactJS时,我收到此错误:-

ERROR in Template execution failed: ReferenceError: window is not defined

ERROR in   ReferenceError: window is not defined

  - MyJavascript.js:17 window
    /src/MyJavascript.js:17:12

  - MyJavascript.js:414 Object.<anonymous>
    /src/MyJavascript.js:414:3 

ReactJS代码:

import './css/app.css';
import React from 'react';
import {hot} from 'react-hot-loader';
import Helmet from 'react-helmet';

import file from './MyJavascript.js';

class App extends React.Component {

    constructor() {
        super();
        this.handleButtonColor = this.handleButtonColor.bind(this);
     };
........

JavaScript代码:

(function() {

    var _ab = window.abtest;

    var _tests = {};

    var abtest = function (testname, traffic, colorslices) {
      if (_tests.hasOwnProperty(testname)) {
        return _tests[testname];
      }

      if (typeof traffic === 'undefined') {
        traffic = 1;
      }

      _tests[testname] = new Test(testname, traffic);

      if (colorslices && colorslices.length) {
        _tests[testname].slices(colorslices);
      }

      return _tests[testname];
    };


    abtest.clear = function () {
      for (var test in _tests) {
        if (_tests.hasOwnProperty(test)) {
          _tests[test].clear();
        }
      }

      _tests = {};
    };

    abtest.events = new Events();

    abtest.config = {
      STORAGE_PREFIX: 'ab:'
    };

    var storageSupported = function (type) {
      var test = 'test';
      try {
        window[type + 'Storage'].setItem(test, test);
        window[type + 'Storage'].removeItem(test);
        return true;
      }
      catch (e) {
        return false;
      }
    };

    function Events() {
      this._events = {};
    }

    Events.prototype.trigger = function (name) {
      var args = Array.prototype.slice.call(arguments, 1);

      if (this._events.hasOwnProperty(name)) {
        for (var x = 0, len = this._events[name].length; x < len; x++) {
          this._events[name][x].apply(window, args);
        }
      }
    };

    Events.prototype.on = function (name, callback) {
      if (!this._events.hasOwnProperty(name)) {
        this._events[name] = [];
      }

      this._events[name].push(callback);
    };

    function Slice (name) {
      this.name = name;
    }

    Slice.prototype.toString = function () {
      return this.name;
    };

    Slice.prototype.toJSON = function () {
      return {
        name: this.name
      };
    };

    /**
     * Test object.
     *
     * @param {String} name
     * @param {Float}  traffic Amount of traffic to put into the test
     */
    function Test (name, traffic) {
      this.name = name;
      this.traffic = traffic;
      this.slice = null;
      this.storage = localStorage;
      this._slices = {};
    }

    /**
     * Set the test's slices.
     *
     * @param  {Array} slices
     * @return {this}
     */
    Test.prototype.slices = function (slices) {
      if (this.slice !== null) {
        throw new Error('Attempted to add slices to already running test.');
      }

      if (Object.prototype.toString.call(slices) !== '[object Array]') {
        slices = Array.prototype.slice.call(arguments, 0);
      }

      for (var x = 0, len = slices.length; x < len; x++) {
        this.add(new Slice(slices[x]));
      }

      return this;
    };

    /**
     * Add a slice to this test.
     *
     * @param {Slice} slice
     */
    Test.prototype.add = function (slice) {
      this._slices[slice.name] = slice;
      return this;
    };

    /**
     * Run the test. Slices the user into the correct slice. If the user
     * has already been sliced into the test, uses the correct slice.
     *
     * @return {this}
     */
    Test.prototype.run = function (callback) {
      // Check for a URL override and fallback to local storage.
      var slice = this.urlSlice() || this.storedSlice();

      // Check that the slice exists as it's possible that the slice
      // defined in local storage was not defined at runtime.
      if (slice && this.hasSlice(slice)) {
        this.slice = this.getSlice(slice);
      }

      // Make sure the user belongs in the test.
      else if (Math.random() > this.traffic) {
        this.slice = new Slice('control');
        abtest.events.trigger('start', this);
      }

      // Choose a slice for the user.
      else {
        this.slice = this.chooseSlice();
        abtest.events.trigger('start', this);
      }

      // Save the slice to local storage.
      this.storage.setItem(this.key(), this.slice.name);

      if (typeof callback === 'function') {
        callback.call(this);
      }

      abtest.events.trigger('run', this);

      return this;
    };

    /**
     * Select a slice for the user.
     *
     * @return {Slice}
     */
    Test.prototype.chooseSlice = function () {
      var slices = [];

      // Get an array of all slice names.
      for (var slice in this._slices) {
        if (this._slices.hasOwnProperty(slice)) {
          slices.push(slice);
        }
      }

      if (slices.length === 0) {
        return new Slice('control');
      }

      var index = Math.floor(Math.random() / (1.0 / slices.length));
      return this.getSlice(slices[index]);
    };

    /**
     * Check if a test includes a slice.
     *
     * @param  {String}  name
     * @return {Boolean}
     */
    Test.prototype.hasSlice = function (name) {
      return (name === 'control' && this.traffic < 1) || this._slices.hasOwnProperty(name);
    };

    /**
     * Get a slice by name.
     *
     * @param  {String} name
     * @return {Slice}
     */
    Test.prototype.getSlice = function (name) {
      return name === 'control' ? new Slice('control') : this._slices[name];
    };

    /**
     * Get a slice from the URL. Returns false if the URL
     * does not contain a slice.
     *
     * @return {String|Boolean}
     */
    Test.prototype.urlSlice = function () {
      var hash = window.location.hash;
      var search = window.location.search;
      var match;

      // Matches '<prefix>:<test>=<slice>'
      // TOOO: Improve this regex. Define what a valid slice name is.
      var re = new RegExp('(' + this.key() + ')=([\\w0-9]+)');

      if (match = hash.match(re)) {
        return match[2];
      }
      else if (match = search.match(re)) {
        return match[2];
      }

      return false;
    };

    /**
     * Retrieve a slice from local storage. Returns null if there is no slice in
     * local storage.
     *
     * @return {String|null}
     */
    Test.prototype.storedSlice = function () {
      return this.storage.getItem(this.key());
    };

    /**
     * Get the key for the test.
     *
     * @return {String}
     */
    Test.prototype.key = function () {
      return abtest.config.STORAGE_PREFIX + this.name;
    };

    /**
     * String representation of this test.
     *
     * @return {String}
     */
    Test.prototype.toString = function () {
      return this.key();
    };

    /**
     * Clear this test from local storage.
     */
    Test.prototype.clear = function () {
      this.storage.removeItem(this.key());
    };

    /**
     * Load a stylesheet.
     *
     * @param  {String} href
     */
    Test.prototype.style = function (href) {
      var style = document.createElement('link');
      style.rel = 'stylesheet';
      style.href = href;
      document.head.appendChild(style);
      return this;
    };

    /**
     * Load a script.
     *
     * @param  {String} src
     */
    Test.prototype.script = function (src, async) {
      var script = document.createElement('script');
      script.type = 'text/javascript';
      script.async = (typeof async === 'undefined') ? true : !!async;
      script.src = src;
      var firstScript = document.getElementsByTagName('script')[0];
      firstScript.parentNode.insertBefore(script, firstScript);
      return this;
    };

    abtest.Test = Test;
    abtest.Slice = Slice;
    abtest.Storage = Storage;
    abtest.Events = Events;


    if (typeof module !== 'undefined' && module.exports && typeof require !== 'undefined') {
      module.exports = abtest;
    }
    else if (typeof define === 'function' && define.amd) {
      define('ab', function () {
        return abtest;
      });
    }
    else {
      window.abtest = abtest;
    }

    })();

请让我知道如何在ReactJS代码中成功调用JS函数(具有窗口,存储空间等)。还有其他替代方法可以实现这一目标吗?

0 个答案:

没有答案