我想在反应JSX中创建一个年份列表
我有一个Jquery的代码,请看下面的内容。
var minOffset = 0, maxOffset = 60; // Change to whatever you want
var thisYear = (new Date()).getFullYear();
var select = $('<select>');
for (var i = minOffset; i <= maxOffset; i++) {
var year = thisYear - i;
$('<option>', {value: year, text: year}).appendTo(select);
}
select.appendTo('body');
答案 0 :(得分:1)
class DropDown extends Component {
render() {
let minOffset = 0, maxOffset = 10;
let thisYear = (new Date()).getFullYear();
let allYears = [];
for(let x = 0; x <= maxOffset; x++) {
allYears.push(thisYear - x)
}
const yearList = allYears.map((x) => {return(<option key={x}>{x}</option>)});
return(
<div>
<select>
{yearList}
</select>
</div>
);
}
}
这可能不是最佳解决方案,但这只是为了让您了解如何做到这一点。
答案 1 :(得分:0)
首先,在数组中生成所有需要的年份
const year = (new Date()).getFullYear();
const years = Array.from(new Array(20),( val, index) => index + year);
多年后,您可以遍历数组并将其列在select
控件中。
请考虑以下代码段
constructor(props){
super(props);
const year = (new Date()).getFullYear();
this.years = Array.from(new Array(20),(val, index) => index + year);
}
render() {
return(
...
<select>
{
this.years.map((year, index) => {
<option key={`year${index}`} value={year}>{year}</option>
})
}
</select>
...
);
}
希望这会有所帮助!
答案 2 :(得分:0)
这可能会有所帮助。确保正确设置正确的状态并在onHandleChange中处理更新。
const minOffset = 0;
const maxOffset = 60;
class DatePicker extends React.Component {
constructor() {
super();
const thisYear = (new Date()).getFullYear();
this.state = {
thisYear: thisYear,
selectedYear: thisYear
}
}
onHandleChange = (evt) => {
// Handle Change Here
// alert(evt.target.value);
this.setState({ selectedYear: evt.target.value });
};
render() {
const { thisYear, selectedYear } = this.state;
const options = [];
for (let i = minOffset; i <= maxOffset; i++) {
const year = thisYear - i;
options.push(<option value={year}>{year}</option>);
}
return (
<div>
<select value={this.selectedYear} onChange={this.onHandleChange}>
{options}
</select>
</div>
);
}
}
/*
* Render the above component into the div#app
*/
ReactDOM.render(<DatePicker />, document.getElementById('app'));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></app>
&#13;
答案 3 :(得分:0)
另一种方式:
getDropList = () => {
const year = new Date().getFullYear();
return (
Array.from( new Array(50), (v,i) =>
<option key={i} value={year+i}>{year+i}</option>
)
);
};