我正在使用React Native Picker来显示月份数字列表。
我试图在加载选择器时显示当前月份(在这种情况下02 (February)
)。
但是,在加载屏幕时,它总是显示01
(一月)而不是02
(二月)。
另一件事是,即使标签显示
01
(一月),选择器值仍然保持为02
(二月)。
如果有人可以解决这个问题,那将非常有帮助。
这是下面提供的代码片段:
const currentDate = new Date();
const currentMonth = currentDate.getMonth() + 1;
export default class AdminNews extends Component {
constructor(props) {
super(props);
this.state = {
date: {
month: currentMonth,
},
}
}
renderMonthPickerItem() {
//this shows the currentMonth but it overlaps with the other pickerItems.
//which means it shows currentMonth 02 two times
// let pickers = [
// <Picker.Item
// label={currentMonth.toString().padStart(2, '0')}
// value={currentMonth.toString()}
// key={currentMonth} />
// ];
let pickers = [];
for (let month = 1; month <= 12; month++) {
pickers.push(
<Picker.Item label={month.toString().padStart(2, '0')} value={month.toString()} key={month} />
);
}
return pickers;
}
renderMonth() {
return (
<>
<View><Text style={{ fontWeight: 'bold', color: 'grey' }}>Month:</Text></View>
<View style={{ marginVertical: 1 }} />
<View style={{ borderRadius: 5, elevation: 3, backgroundColor: '#FAFAFA' }}>
<Picker
mode="dropdown"
selectedValue={this.state.date.month}
onValueChange={(itemValue, itemIndex) => {
this.setState({
date: {
...this.state.date,
month: itemValue
}
});
this.apiNews();
}}
>
{this.renderMonthPickerItem()}
</Picker>
</View>
</>
);
}
render(){ return( ***other code*** ); }
};
截屏: