You need to enable JavaScript to run this app. React中如何基于react-select下拉币种选择更新表格价格数据
优惠活动
大模型
产品
解决方案
定价
更多

React中如何基于react-select下拉币种选择更新表格价格数据

基于react-select实现表格价格随币种切换的实现方案

核心实现逻辑

  • 用组件状态存储当前选中的币种值,绑定react-select为受控组件,保证切换币种时整个表格自动联动重算
  • 提前维护不同币种和原计价货币(澳元)的汇率映射,切换时自动换算所有价格列的展示值
  • 抽出通用的价格格式化方法,避免每个价格列重复写计算逻辑,减少冗余代码

具体代码实现

  1. 组件初始化部分(状态、汇率配置、选项定义)
import Select from 'react-select';
import { useState } from 'react';

// 汇率配置可根据实际业务替换为接口拉取的动态值
const exchangeRateMap = {
  AUD: 1, // 原JSON数据默认以澳元为计价基准
  USD: 0.66,
  GBP: 0.52,
  EUR: 0.61
}

// 你原本定义的下拉选项保留即可
const currencyOptions = [
  { value: 'USD', label: 'USD' },
  { value: 'GBP', label: 'GBP' },
  { value: 'EUR', label: 'EUR' }
]

function PriceTable() {
  // 存储当前选中的币种,默认初始为原计价澳元
  const [selectedCurrency, setSelectedCurrency] = useState({ value: 'AUD', label: 'AUD' })
  // 原有从JSON加载TableData的逻辑保持不变即可
}
  1. 挂载币种选择器到表格上方区域
{/* 币种切换下拉框 */}
<Select
  value={selectedCurrency}
  onChange={(option) => setSelectedCurrency(option)}
  options={currencyOptions}
  className="max-w-[200px] mb-4"
/>
  1. 改造原有表格的渲染逻辑
{TableData.map((tableDetails, index) => {
  const currentRate = exchangeRateMap[selectedCurrency.value]
  // 通用价格格式化方法,统一处理数值换算、精度截断
  const formatPrice = (originalPrice) => {
    const priceNum = Number(originalPrice)
    if (isNaN(priceNum)) return originalPrice
    return (priceNum * currentRate).toFixed(2)
  }
  return (
    // 补充React列表必需的key属性,用唯一值替代索引避免渲染警告
    <div key={tableDetails.Sample_Postcode}>
      <table className="table-fixed w-full">
        <tbody>
          <tr>
            <td id="tablebody1">{tableDetails.Sample_Postcode}</td>
            <td id="tablebody2">{tableDetails.Australia}</td>
            <td id="price1">{formatPrice(tableDetails.Price1)}</td>
            <td>{formatPrice(tableDetails.Price2)}</td>
            <td>{formatPrice(tableDetails.Price3)}</td>
            <td>{formatPrice(tableDetails.Price4)}</td>
            <td>{formatPrice(tableDetails.Price5)}</td>
            <td>{formatPrice(tableDetails.Price6)}</td>
            <td>{formatPrice(tableDetails.Price7)}</td>
            <td>{formatPrice(tableDetails.Price8)}</td>
            <td>{formatPrice(tableDetails.Price9)}</td>
            <td>{formatPrice(tableDetails.Price10)}</td>
          </tr>
        </tbody>
      </table>
    </div>
  )
})}

补充说明

  • 如果你的JSON数据源里已经提前存储了对应每个币种的价格值,不需要汇率换算,只需要把formatPrice里的换算逻辑改成从tableDetails中读取对应币种的价格字段即可
  • 原代码中map渲染的列表没有给外层div加唯一key属性,上线后会触发React的渲染警告,建议替换为业务上唯一的字段作为key(比如Sample_Postcode),不要用数组索引当key
  • 汇率如果需要实时同步行情,可以把静态的汇率表替换为接口请求逻辑,在组件挂载或币种切换时拉取最新值即可

内容的提问来源于stack exchange,提问作者Connor Flynn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.30 14:45:02