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

如何在React JSX中实现年份下拉列表?附jQuery参考代码

React JSX Implementation for Year Dropdown

Here's how you can recreate that year dropdown using React's declarative approach, which avoids direct DOM manipulation like jQuery does:

Basic Uncontrolled Component

This matches the behavior of your original jQuery code, rendering a dropdown with years from the current year back 60 years:

import React from 'react';

const YearDropdown = () => {
  // Define your offset values (same as the jQuery code)
  const minOffset = 0;
  const maxOffset = 60;
  const currentYear = new Date().getFullYear();

  // Generate the array of years to display
  const years = [];
  for (let i = minOffset; i <= maxOffset; i++) {
    years.push(currentYear - i);
  }

  return (
    <select>
      {/* Map over the years array to create option elements */}
      {years.map(year => (
        <option key={year} value={year}>
          {year}
        </option>
      ))}
    </select>
  );
};

export default YearDropdown;

Key Differences from jQuery:

  • Instead of creating DOM elements and appending them manually, we declare what the UI should look like based on our years data array. React handles rendering the elements efficiently.
  • We use the map function to convert each year value into an <option> component. The key prop is required for React to track list items properly (we use the year itself since it's unique).
  • You'll render this component wherever you need it in your React app (e.g., inside a form in another component) instead of appending directly to the <body>.

Optional: Controlled Component (Track Selected Value)

If you need to track the user's selected year in state (common for form handling), add React's useState hook:

import React, { useState } from 'react';

const YearDropdown = () => {
  const minOffset = 0;
  const maxOffset = 60;
  const currentYear = new Date().getFullYear();
  
  // Set default selected year to current year
  const [selectedYear, setSelectedYear] = useState(currentYear);

  const years = [];
  for (let i = minOffset; i <= maxOffset; i++) {
    years.push(currentYear - i);
  }

  return (
    <select 
      value={selectedYear}
      onChange={(e) => setSelectedYear(e.target.value)}
    >
      {years.map(year => (
        <option key={year} value={year}>
          {year}
        </option>
      ))}
    </select>
  );
};

export default YearDropdown;

This way, selectedYear will always reflect the user's choice, and you can use that value in other parts of your component or app.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:13:23