javascript - 如何建立一个简单的美元/欧元反应货币转换器,具有固定的转换率?
问题描述
对于一个练习,我需要构建一个非常简单的货币转换器,它只将货币从美元转换为欧元,反之亦然,设定汇率 (0.91 / 1.09)。我想成为我的 App.js 文件尽可能模块化。另外,我想使用钩子(不是类组件)
我的文件结构:
src
├── components (Holds all components)
│ ├── InputDollar.js (gets Dollar Input)
│ ├── InputEuro.js (gets Euro Input)
│ ├── Button.js (triggers conversion)
│ └── Converter.js (Converts Dollar into Euro or vice versa)
├── App.js (renders all components)
└── Index.js (eventually exports to html "root" id)
我想在这里发布我到目前为止的所有代码会太长,但我共享一个沙箱:https ://codesandbox.io/s/misty-morning-l3y1e?fontsize=14
我认为输入和按钮很好。最有可能有缺陷的是转换器组件——我在下面分享——(因为我很困惑如何传入输入以及如何在 if 语句中编写正确的语法)和应用程序组件,因为我无法显示结果按钮 单击。
转换器.js
import React from "react";
import InputDollar from "./InputDollar"
import InputEuro from "./InputEuro"
function ConvertedValue() {
let converted = function() {
if(<InputDollar>!="") {
ConvertedValue = (<InputDollar />* 0.9)
} else if (<InputEuro>!="") {
ConvertedValue = (<InputEuro />* 1.1)
}
}
return (
<div>
{converted}
</div>
);
}
export default ConvertedValue;
你能帮我完成这个练习,并在可能的情况下注释掉主要功能吗?
解决方案
这是我将如何调整现有代码的方法:
1) 一个<Input>
服务于两个原因的组件。它接受类型和标签以及您的handleChange
方法。
function Input(props) {
const { label, type, handleChange } = props;
function onChange(event) {
// Pass in the type and value
handleChange(type, event.target.value);
}
return (
<div>
<label>{label}</label>
<input onChange={onChange} type="number" />
</div>
);
}
2)在您的<App>
组件中:
function App() {
// Have one state for the converted value
const [ convertedValue, setConvertedValue ] = useState(0);
// Then, when `handleChange` is called, just choose between the
// input type, and set the state
function handleChange(type, value) {
if (type === 'euro') setConvertedValue(value * 1.1);
if (type === 'dollar') setConvertedValue(value * 0.9);
}
return (
<div>
// Using the Input component pass in the type, label, and handleChange
// for the dollar and euro
<Input type="dollar" label="Dollar" handleChange={handleChange} />
<Input type="euro" label="Euro" handleChange={handleChange} />
// Then you can keep the updated converted value here
<div>{convertedValue}</div>
</div>
);
}
希望这是有用的。
推荐阅读
- javascript - 无法解析 Vue 函数中的变量
- android - sqlitejdbc.dll.lck(系统找不到指定的路径)
- scala - 类型不匹配; 找到:org.apache.spark.sql.DataFrame 需要:org.apache.spark.rdd.RDD
- django - DRF:使用 unique_together 时将父子关系序列化为字典而不是列表
- html - 一旦我向 div 添加了不同的名称,下拉菜单就不会显示
- java - 当构建器本身不继承时,使用生成的继承类构建器
- javascript - Highcharts:一次更新多个系列,以获得更流畅的动画
- ios - 谷歌分析,统一。iOS模拟器不发送事件
- angularjs - AngularJS,用于 Bootstrap 4 的 UIB,找不到和加载模板
- cookies - MS Edge 丢弃 cookie