通过ReactJS中的jQuery添加事件时如何获取主要的对象?

时间:2019-05-13 02:38:40

标签: reactjs fullcalendar fullcalendar-scheduler react-rails

我正在使用fullcalendar-scheduler插件来跟踪日历。目前,我已将其与react和rails集成在一起。我试图在更改时添加诸如select(“ months-tab”)标签的事件。但是,当尝试访问context对象时,事件内部什么也没得到。但是我在context的活动之外得到了viewRender

import React from "react";
import PropTypes from "prop-types";
import axios from "axios";

class TestCalendar extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      cars: [],
      events: [],
      price: [],
      selectDates: [],
      startDate: moment(),
      endDate: moment().add(3, 'years')
    }
  }

  componentDidMount() {
    const headers = {
      'Content-Type': 'application/json'
    }

    axios.get('/api/v1/test_calendars?date_from=' + this.state.startDate.format(), { headers: headers })
    .then(res => {
      const cars = res.data;
      this.setState({ cars });
    });

    axios.get('/api/v1/test_calendars/events?date_from=' + this.state.startDate.format(), { headers: headers })
    .then(res => {
      const events = res.data;
      this.setState({ events });
    });

    axios.get('/api/v1/test_calendars/prices?date_from=' + this.state.startDate.format(), { headers: headers })
    .then(res => {
      const price = res.data;
      this.setState({ price });
    });
    this.updateEvents(this.props.hidePrice);
  }

  componentDidUpdate() {
    console.log('componentDidUpdate');
    this.updateEvents(this.props.hidePrice);
    console.log(this.state.cars);
  }

  componentWillUnmount() {
    $('#test_calendar').fullCalendar('destroy');
  };

  handleChange(e) {
    debugger;
  }

  updateEvents(hidePrice) {
    function monthSelectList() {
      let select = '<div class="Select select-me"><select id="months-tab" class="Select-input">' +
                    '</select></div>'
      return select
    }

    function getDates(startDate, stopDate) {
      var dateArray = [];
      while(startDate.format('YYYY-MM-DD') <= stopDate.format('YYYY-MM-DD')) {
        dateArray.push(startDate.format('YYYY-MM'));
        startDate = startDate.add(1, 'days');
      };

      return dateArray;
    }

    const self = this;
    const context = this;
    $('#test_calendar').fullCalendar('destroy');
    $('#test_calendar').fullCalendar({
      selectable: false,
      defaultView: 'timelineEightDays',
      defaultDate: this.props.defaultDate,
      views: {
        timelineEightDays: {
          type: 'timeline',
          duration: { days: 8 },
          slotDuration: '24:00'
        }
      },
      header: {
        left: 'prev',
        right: 'next'
      },
      viewRender: function(view, element) {
        let uniqueDates;
        //This displays the main component obj with props
        context;
        $("span:contains('Cars')").empty().append(
          monthSelectList()
        );

        $("#months-tab").on("change", function() {
          // This does nothing. 
          context
          let index, optionElement, month, year, goToDate;

          index = this.selectedIndex;
          optionElement = this.childNodes[index];
          month = optionElement.getAttribute("data-month");
          year = optionElement.getAttribute("data-year");
          goToDate = moment([year, (month - 1), 1]).format("YYYY-MM-DD");
          $("#test_calendar").fullCalendar('gotoDate', moment(goToDate));
          $("#months-tab").find("option[data-month=" + month + "][data-year=" + year + "]").prop("selected", true);
          this.handleChange.bind(this)
        });

        let dates = getDates(moment(), moment().add(3, "years"));
        uniqueDates = [...new Set(dates)];
        $('#months-tab option').remove();
        $.each(uniqueDates, function(i, date) {
          $('#months-tab').append($('<option>', {
          value: i,
          text: moment(date).format('MMMM') + " " + moment(date).format('YYYY'),
          'data-month': moment(date).format('MM'),
          'data-year': moment(date).format('YYYY'),
          }));
        });
      },
      resources: this.state.cars,
      resourceRender: function(resourceObj, labelTds, bodyTds) {
        labelTds.css('background-image', "url(" + resourceObj.header_image + ")");
        labelTds.css('background-size', "160px 88px");
        labelTds.css('background-repeat', "no-repeat");
        labelTds.css("border-bottom", "1px solid");
        labelTds.addClass('resource-render');
        labelTds.children().children().addClass("car-name");
      },
      resourceLabelText: 'Cars',
      dayClick: function(date, jsEvent, view, resource) {
      },
      dayRender: function(date, cell){
        cell.addClass('dayrender');
      },
      select: function(startDate, endDate, jsEvent, view, resource) {
          // Get 'self' object here
      },
      events: this.state.events.concat(this.state.price),
      eventRender: function(event, element, view){
      },
      schedulerLicenseKey: 'CC-Attribution-NonCommercial-NoDerivatives'
    });

    // Should stay after full component is initialized to avoid fc-unselectable class on select tag for months
    $("#months-tab").on("mousedown click", function(event){event.stopPropagation()});
    $(".prev-link").on("click", function(event){event.stopPropagation()});
    $(".next-link").on("click", function(event){event.stopPropagation()});
  }

  render () {
    return (
      <div id='test_calendar'>
      </div>
    );
  }
}

export default TestCalendar;

我们如何在jquery事件中获取主对象?另外,在反应中处理这种情况的最佳方法是什么?

0 个答案:

没有答案