React JS中解析XML Feed并获取cube元素属性构建货币转换器
在React中遍历XML的cube元素并实现货币转换器
嘿,我来帮你搞定这个货币转换器的问题!要实现遍历XML里的cube元素、提取目标属性并搭建可自动转换的转换器,咱们可以分步骤来操作:
1. 解析XML并定位cube元素
首先得用浏览器内置的DOMParser来解析XML数据。拿到解析后的文档对象后,咱们可以通过属性选择器精准定位所有带currency和rate属性的cube元素——这样能避免误拿到其他层级的空cube。
2. 遍历提取属性并存储
因为querySelectorAll返回的是类数组的HTMLCollection,咱们需要把它转成数组,再用map方法遍历每个cube元素,用getAttribute()提取需要的属性值,最后把这些数据存在组件的state里,方便后续渲染和计算。
3. 构建UI并实现自动转换逻辑
用state里的货币数据渲染下拉选项,监听用户输入的价格和选中的货币,实时计算转换后的金额。
完整代码示例
import React, { Component } from 'react'; class CurrencyConverter extends Component { state = { currencies: [], selectedCurrency: '', inputPrice: '', convertedPrice: 0 }; componentDidMount() { // 替换成你实际获取到的XML字符串 const xmlData = ` <gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01" xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref"> <gesmes:subject>Reference rates</gesmes:subject> <gesmes:Sender> <gesmes:name>European Central Bank</gesmes:name> </gesmes:Sender> <Cube> <Cube time="2024-05-20"> <Cube currency="USD" rate="1.0875"/> <Cube currency="JPY" rate="162.03"/> <Cube currency="GBP" rate="0.8593"/> <!-- 剩余20+个cube元素 --> </Cube> </Cube> </gesmes:Envelope> `; // 解析XML const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xmlData, 'text/xml'); // 精准获取带目标属性的cube元素 const cubeElements = xmlDoc.querySelectorAll('Cube[currency][rate]'); // 转换为数组并提取属性 const currencies = Array.from(cubeElements).map(cube => ({ currency: cube.getAttribute('currency'), rate: parseFloat(cube.getAttribute('rate')) })); // 更新state,默认选中第一个货币 this.setState({ currencies, selectedCurrency: currencies[0]?.currency || '' }); } // 处理输入价格变化 handleInputChange = (e) => { const inputPrice = parseFloat(e.target.value) || 0; this.setState({ inputPrice }, this.calculateConvertedPrice); }; // 处理选中货币变化 handleCurrencyChange = (e) => { this.setState({ selectedCurrency: e.target.value }, this.calculateConvertedPrice); }; // 计算转换后的价格(这里默认基准货币是欧元,可根据需求调整) calculateConvertedPrice = () => { const { inputPrice, selectedCurrency, currencies } = this.state; const selectedRate = currencies.find(curr => curr.currency === selectedCurrency)?.rate || 1; // 如果是从目标货币转欧元,就改成 inputPrice / selectedRate const convertedPrice = (inputPrice * selectedRate).toFixed(2); this.setState({ convertedPrice }); }; render() { const { currencies, selectedCurrency, inputPrice, convertedPrice } = this.state; return ( <div style={{ padding: '20px', maxWidth: '400px', margin: '0 auto' }}> <h2>货币转换器</h2> <div> <label>输入价格(欧元):</label> <input type="number" value={inputPrice} onChange={this.handleInputChange} style={{ marginLeft: '10px', padding: '5px' }} step="0.01" /> </div> <div style={{ marginTop: '15px' }}> <label>选择目标货币:</label> <select value={selectedCurrency} onChange={this.handleCurrencyChange} style={{ marginLeft: '10px', padding: '5px' }} > {currencies.map(curr => ( <option key={curr.currency} value={curr.currency}> {curr.currency} (1欧元 = {curr.rate} {curr.currency}) </option> ))} </select> </div> <div style={{ marginTop: '20px', fontSize: '18px' }}> 转换后金额: {convertedPrice} {selectedCurrency} </div> </div> ); } } export default CurrencyConverter;
关键细节说明
querySelectorAll('Cube[currency][rate]'):通过属性选择器精准筛选同时带有currency和rate的cube元素,避免拿到父级无属性的cube。Array.from():把类数组的HTMLCollection转成真正的数组,这样就能用map、find等数组方法处理数据。- 容错处理:当输入非数字时默认设为0,找不到选中货币的汇率时默认用1,避免页面报错。
- 转换逻辑可调整:如果你的XML里汇率基准不是欧元,只需要修改
calculateConvertedPrice里的计算方式即可。
内容的提问来源于stack exchange,提问作者Robert Young
相关产品推荐
相关产品推荐

