如何在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
yearsdata array. React handles rendering the elements efficiently. - We use the
mapfunction to convert each year value into an<option>component. Thekeyprop 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
相关产品推荐
相关产品推荐

