React中Material UI报错:无法解析@material-ui/pickers模块求助
The error you're seeing happens because @material-ui/pickers is a deprecated package—Material UI moved all date/time picker functionality to a dedicated, maintained package called @mui/x-date-pickers starting from version 5. Here's how to fix this properly, building on your existing solution for the @date-io/date-fns issue:
Step 1: Replace Deprecated Packages
First, remove the old (and unmaintained) pickers package along with the outdated date adapter, then install the official replacements:
# Uninstall old packages (if they're present) npm uninstall @material-ui/pickers @date-io/date-fns # Install the new pickers package and compatible date-fns npm install @mui/x-date-pickers date-fns
Step 2: Update Your Code to Use the New Components
The import paths and component names have changed slightly. Here's the revised version of your code that works with the new package:
import 'date-fns'; import React from 'react'; import Grid from '@material-ui/core/Grid'; import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider'; import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns'; import { DatePicker, TimePicker } from '@mui/x-date-pickers'; function MaterialUITest() { const [selectedDate, setSelectedDate] = React.useState(new Date('2014-08-18T21:11:54')); const handleDateChange = (date) => { setSelectedDate(date); }; return ( <LocalizationProvider dateAdapter={AdapterDateFns}> <Grid container justify="space-around"> <DatePicker disableToolbar variant="inline" inputFormat="MM/dd/yyyy" margin="normal" id="date-picker-inline" label="Date picker inline" value={selectedDate} onChange={handleDateChange} keyboardButtonProps={{ 'aria-label': 'change date', }} /> <DatePicker margin="normal" variant="dialog" inputFormat="MM/dd/yyyy" id="date-picker-dialog" label="Date picker dialog" value={selectedDate} onChange={handleDateChange} keyboardButtonProps={{ 'aria-label': 'change date', }} /> <TimePicker margin="normal" id="time-picker" label="Time picker" value={selectedDate} onChange={handleDateChange} keyboardButtonProps={{ 'aria-label': 'change time', }} /> </Grid> </LocalizationProvider> ); } export default MaterialUITest;
Key Changes Explained:
MuiPickersUtilsProvideris replaced withLocalizationProvider, which usesAdapterDateFns(the updated date adapter for date-fns)KeyboardDatePickeris now justDatePicker—we use thevariantprop to specify inline/dialog behaviorKeyboardTimePickeris simplified toTimePicker- The format prop is now
inputFormatinstead offormat
This should resolve the module not found error and keep your pickers working with the latest, supported Material UI tools.
内容的提问来源于stack exchange,提问作者Daniel Janowski

