我使用来自材料ui的选择器进行此类学习。 我无法打印当前选择的项目
import React, { useState } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import { MuiPickersUtilsProvider, DatePicker } from "@material-ui/pickers";
import MomentUtils from "@date-io/moment";
const styles = theme => ({
container: {
display: 'flex',
flexWrap: 'wrap',
},
textField: {
marginLeft: theme.spacing(1),
marginRight: theme.spacing(1),
width: 200,
},
});
class YearPickerClass extends React.Component {
state = {
yearFrom: new Date(1900, 1, 1, 1, 1, 1, 1),
yearTo: new Date(1950, 1, 1, 1, 1, 1, 1),
}
componentWillReceiveProps(props) {
console.log("willReceive")
console.log(props)
}
handleChange = (date) => {
console.log("date")
console.log(date) //prints 1900 even if I select a different year
}
render() {
const classes = this.props;
var from = new Date(1900, 1, 1, 1, 1, 1, 1);
var to = new Date(1950, 1, 1, 1, 1, 1, 1);
return (
<form className={classes.container} noValidate>
<MuiPickersUtilsProvider utils={MomentUtils}>
<DatePicker
key="yearFrom"
views={["year"]}
label="Year From"
value={this.state.yearFrom}
onChange={this.handleChange}
animateYearScrolling
minDate={from}
maxDate={to}
/>
</MuiPickersUtilsProvider>
</form>
);
}
}
export default (YearPickerClass);
有什么想法如何在handleChange函数中获取当前选定的项目?
答案 0 :(得分:0)
一旦您将时刻转换为日期,您将看到您实际上在handleChange函数中获得了新值:
handleChange = date => {
console.log(moment(date).format('YYYY'));
};
请查看它的工作原理: https://codesandbox.io/embed/magical-snowflake-4fzgn