首页 > 解决方案 > 我应该使用事件监听器还是应该在 React 的生命周期方法中?

问题描述

我有一个呈现表单的组件。这种形式可以吐出一组预定机场之间的距离。

{
  JFK: { LAX: 2475, LAS: 2248, PDX: 2454 },
  LAX: { JFK: 2475, LAS: 236, PDX: 834 },
  LAS: { JFK: 2248, LAX: 236, PDX: 763 },
  PDX: { JFK: 2454, LAS: 763, LAX: 834 },
}

这个对象代表我将像在 API 中一样获取的数据。

该表单包含两个选择/选项下拉菜单。一个代表起点,另一个代表终点。

在此处输入图像描述 我将所有相关代码放在一个名为的函数中,该函数handleSumbit应该触发我正在导入的函数,该函数将输出所选机场之间的距离。

handleSubmit(e) {
    e.preventDefault();

    function returnAirPort(airport) {
      return airport;
    }

    var starting = document.getElementById('starting'),
        destination = document.getElementById('destination'),
        startingEventVal,
        destinationEventVal;

    starting.addEventListener('change', function(e) {
      startingEventVal = returnAirPort(e.srcElement.value);
      console.log('startingEventVal', startingEventVal);
    });

    destination.addEventListener('change', function(e) {
      destinationEventVal = returnAirPort(e.srcElement.value);
      console.log('destinationEventVal', destinationEventVal);
    });

    (function(startingEventVal, destinationEventVal) {
      var distance = IntentMedia.Distances.distance_between_airports(startingEventVal, destinationEventVal);
      console.log("distance", distance);

      document.getElementById('feedback').innterHTML = distance
    })(startingEventVal, destinationEventVal);
  }

现在我在控制台中得到的只是-1; 如果无法确定距离或您输入了无效的机场,您将获得的价值?!我不应该至少在 DOM 中得到渲染吗?

这是表格:

      <form onSubmit={this.handleSubmit}>
        {console.log(airportNames)}
        <div className="row">
          <div className="twelve columns">
            <h2>The following are our available flights</h2>
            <p>
              If your airport exists in the following dropdown we can supply the distance in miles or Kilometers below
              between them.
            </p>

            <label htmlFor="exampleEmailInput">Your Starting Airport</label>
            <select id="starting" className="u-full-width">
              <option defaultValue> -- select an option -- </option>
              {airportNames}
            </select>
          </div>
          <div className="twelve columns">
            <label htmlFor="exampleEmailInput">Your destination</label>
            <select id="destination" className="u-full-width">
              <option defaultValue> -- select an option -- </option>

              {airportNames}
            </select>
          </div>
        </div>
        <p id="feedback" />
        <button>Submit</button>
      </form>

所以我的问题是如何向 DOM 呈现所选机场之间的距离?

标签: javascriptreactjsdom-eventsreact-lifecycle

解决方案


推荐阅读