gpt4 book ai didi

javascript - 如何构建一个简单的具有固定转换比率的美元/欧元 react 货币转换器?

转载 作者:行者123 更新时间:2023-12-02 22:52:57 29 4
gpt4 key购买 nike

为了练习,我需要构建一个非常简单的货币转换器,仅以设定汇率 (0.91/1.09) 将货币从美元转换为欧元,反之亦然。我希望我的 App.js 文件尽可能模块化。另外,我想使用钩子(Hook)(不是类组件)

我的文件结构:

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 语句中编写正确的语法)和应用程序组件,因为我无法在其上显示结果按钮点击。

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

希望这有用。

Sandbox

关于javascript - 如何构建一个简单的具有固定转换比率的美元/欧元 react 货币转换器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58115991/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com