javascript - 我应该使用事件监听器还是应该在 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 呈现所选机场之间的距离?
解决方案
推荐阅读
- ios - 使用 NotificationCenter 的加载器
- javascript - 在打开的窗口中从 angularJS 捕获 url
- php - 如何选择特定列的最小时间和最大时间?
- angular - 角度 4 防止在部分路径上显示组件
- javascript - 离子存储实现:获取和设置
- robotframework - 如何使用机器人框架自动化桌面应用程序
- amazon-web-services - 如何在 CodeBuild 中从 Docker Store 运行 docker 容器?
- php - exec('top', $output) 返回一个空数组?
- mysql - mysql触发删除相同的ID
- php - 在数据库中存储会话数组