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

React Native函数式组件中CalendarStrip多语言切换失效求助

修复CalendarStrip语言切换不同步问题

问题根源

你的代码仅引入了moment的语言包,但未主动设置moment的全局语言环境;切换回英语时也没有重置locale,同时CalendarStrip组件不会自动感知moment locale的变化,导致语言无法同步更新。

修复步骤

  1. 调用moment.locale()主动设置全局语言,匹配用户选择的语种
  2. 处理英语默认场景,当用户语言不是西语(ES)或意语(IT)时,重置回英语环境
  3. 给CalendarStrip添加key属性,语言变更时强制组件重新渲染,确保新语言生效

修改后的完整代码

import { Moment } from 'moment';
import React, { FunctionComponent, useContext, useEffect } from 'react';
import { NETWORK_ONLY, useQuery } from 'relay-hooks';
import { AuthenticationContext } from '../providers/authentication/AuthenticationProvider';
import CalendarStrip from 'react-native-calendar-strip';
import moment from 'moment';

import USER_BY_ID, {
  relayGetUserByIdQuery,
} from '../__generated__/relayGetUserByIdQuery.graphql';
interface Props {
  selectedDate: Date | Moment;
  setSelectedDate: React.Dispatch<React.SetStateAction<Date | Moment>>;
}

const WeeklyCalendar: FunctionComponent<Props> = (props) => {
  const { selectedDate, setSelectedDate } = props;
  const { userData, refreshQuery } = useContext(AuthenticationContext);

  const { data } = useQuery<relayGetUserByIdQuery>(
    USER_BY_ID,
    { id: userData?.userId || ''},
    { fetchPolicy: NETWORK_ONLY }
  );

  useEffect(() => {
    refreshQuery();
    const userLang = data?.user?.language;
    // 根据用户语言设置moment全局locale
    if (userLang === 'ES') {
      require('moment/locale/es');
      moment.locale('es');
    } else if (userLang === 'IT') {
      require('moment/locale/it');
      moment.locale('it');
    } else {
      // 切换回默认英语环境
      moment.locale('en');
    }
  }, [data?.user?.language])

  return (
    <CalendarStrip
      // 添加key属性,语言变化时强制组件重渲染
      key={data?.user?.language || 'en'}
      scrollable
      style={{ height: 75 }}
      calendarHeaderStyle={{
        color: '#3D3D3D',
        fontSize: 16,
        fontWeight: '500',
      }}
      dateNumberStyle={{ color: '#3D3D3D' }}
      dateNameStyle={{ color: '#3D3D3D' }}
      highlightDateNumberStyle={{ color: 'white' }}
      highlightDateNameStyle={{ color: 'white' }}
      highlightDateContainerStyle={{
        borderRadius: 10,
      }}
      iconContainer={{ flex: 0.1 }}
      numDaysInWeek={7}
      daySelectionAnimation={{
        type: 'background',
        duration: 200,
        highlightColor: '#2975D6',
      }}
      selectedDate={selectedDate}
      onDateSelected={(date) => setSelectedDate(date)}
    />
  );
};

export default WeeklyCalendar;

关键修改点说明

  • 在useEffect中新增moment.locale()调用,明确设置当前语言环境
  • 补充英语默认场景的处理,确保切换回英语时生效
  • 给CalendarStrip添加key={data?.user?.language || 'en'},语言变更时组件会重新初始化,从而读取新的moment locale进行渲染

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 20:20:36