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

如何使用JavaScript在React Native中从月份列表选中当前月份

React Native 从给定月份数组选中当前月份实现方案

实现逻辑

  • JavaScript 内置Date对象的getMonth()方法返回值范围为0~11,对应1月到12月,需要加1后转成字符串,和你提供的数组中value字段格式对齐
  • 遍历月份数组,筛选出value和当前月份字符串匹配的项即可

代码示例

你提供的月份数组定义:

const Month = [
  { value: "1", label: "JAN", key: "JAN" },
  { value: "2", label: "FEB", key: "FEB" },
  { value: "3", label: "MAR", key: "MAR" },
  { value: "4", label: "APRIL", key: "APRIL" },
  { value: "5", label: "MAY", key: "MAY" },
  { value: "6", label: "JUN", key: "JUN" },
  { value: "7", label: "JUL", key: "JUL" },
  { value: "8", label: "AUG", key: "AUG" },
  { value: "9", label: "SEP", key: "SEP" },
  { value: "10", label: "OCT", key: "OCT" },
  { value: "11", label: "NOV", key: "NOV" },
  { value: "12", label: "DEC", key: "DEC" }
];

匹配当前月份的核心代码:

// 获取当前月份,转成和value字段匹配的字符串格式
const currentMonthValue = String(new Date().getMonth() + 1);
// 匹配对应月份项
const selectedCurrentMonth = Month.find(item => item.value === currentMonthValue);

Picker选择器默认选中当前月份示例(以@react-native-picker/picker为例)

import { View } from 'react-native';
import { Picker } from '@react-native-picker/picker';
import { useState } from 'react';

const MonthSelector = () => {
  // 初始化直接默认选中当前月份
  const [selectedMonth, setSelectedMonth] = useState(String(new Date().getMonth() + 1));

  return (
    <View>
      <Picker
        selectedValue={selectedMonth}
        onValueChange={(value) => setSelectedMonth(value)}
      >
        {Month.map(item => (
          <Picker.Item label={item.label} value={item.value} key={item.key} />
        ))}
      </Picker>
    </View>
  )
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 06:54:08