You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React Native中使用Context实现多币种功能

React Native多币种切换实现(基于Context API)

用Context API来做确实是最省心的方案,能全局管理货币状态,不用层层传参。下面是完整的实现步骤:

1. 创建货币Context与全局Provider

新建一个CurrencyContext.js文件,封装状态和操作方法:

import React, { createContext, useContext, useState, useCallback } from 'react';

const CurrencyContext = createContext();

// 可扩展更多币种的配置
const CURRENCY_CONFIGS = {
  USD: { symbol: '$', code: 'USD', locale: 'en-US' },
  CNY: { symbol: '¥', code: 'CNY', locale: 'zh-CN' },
  EUR: { symbol: '€', code: 'EUR', locale: 'de-DE' }
};

export const CurrencyProvider = ({ children }) => {
  // 初始货币可从本地存储读取,这里默认设为CNY
  const [currentCurrency, setCurrentCurrency] = useState('CNY');

  // 切换货币的方法
  const switchCurrency = useCallback((currencyCode) => {
    if (CURRENCY_CONFIGS[currencyCode]) {
      setCurrentCurrency(currencyCode);
      // 可选:用AsyncStorage持久化用户选择
      // AsyncStorage.setItem('selectedCurrency', currencyCode);
    }
  }, []);

  // 格式化金额的核心方法
  const formatAmount = useCallback((amount) => {
    const config = CURRENCY_CONFIGS[currentCurrency];
    return new Intl.NumberFormat(config.locale, {
      style: 'currency',
      currency: config.code,
      currencyDisplay: 'symbol'
    }).format(amount);
  }, [currentCurrency]);

  return (
    <CurrencyContext.Provider value={{
      currentCurrency,
      switchCurrency,
      formatAmount,
      currencySymbol: CURRENCY_CONFIGS[currentCurrency].symbol
    }}>
      {children}
    </CurrencyContext.Provider>
  );
};

// 自定义Hook,简化组件调用
export const useCurrency = () => useContext(CurrencyContext);

2. 在App根组件中注入Provider

把Provider包裹在App最外层,确保所有子组件都能访问货币状态:

import { CurrencyProvider } from './CurrencyContext';

export default function App() {
  return (
    <CurrencyProvider>
      {/* 你的页面/组件层级 */}
      <MainScreen />
    </CurrencyProvider>
  );
}

3. 在业务组件中使用

示例:货币选择按钮与金额展示组件

import { useCurrency } from './CurrencyContext';
import { View, Text, Button } from 'react-native';

const MainScreen = () => {
  const { switchCurrency, formatAmount, currencySymbol } = useCurrency();
  const testAmount = 1234.56;

  return (
    <View style={{ padding: 20, gap: 15 }}>
      <Text>当前货币符号:{currencySymbol}</Text>
      <Text>格式化后金额:{formatAmount(testAmount)}</Text>
      
      <View style={{ flexDirection: 'row', gap: 10 }}>
        <Button title="$ 切换美元" onPress={() => switchCurrency('USD')} />
        <Button title="¥ 切换人民币" onPress={() => switchCurrency('CNY')} />
        <Button title="€ 切换欧元" onPress={() => switchCurrency('EUR')} />
      </View>
    </View>
  );
};

关键细节说明

  • 用Intl.NumberFormat原生API处理格式化,自动适配不同币种的千分位、小数位、符号位置,不用自己写正则逻辑。
  • 持久化用户选择:在Provider初始化时,通过AsyncStorage或MMKV读取存储的货币代码,替换默认值即可。
  • 扩展币种:直接在CURRENCY_CONFIGS中添加新币种的配置,无需修改其他逻辑。

内容的提问来源于stack exchange,提问作者Anjali Deshmukh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 08:24:57