首页 > 解决方案 > 如何建立一个简单的美元/欧元反应货币转换器,具有固定的转换率?

问题描述

对于一个练习,我需要构建一个非常简单的货币转换器,它只将货币从美元转换为欧元,反之亦然,设定汇率 (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;

你能帮我完成这个练习,并在可能的情况下注释掉主要功能吗?

标签: javascriptreactjsreact-hooks

解决方案


这是我将如何调整现有代码的方法:

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>
  );
}

希望这是有用的。

沙盒


推荐阅读