简体   繁体   中英

How Do I Set The Current Date In A Material-UI TextField

If I set type="date" on a TextField I can initialise it with a string.

https://codesandbox.io/s/9y6yz462op

const values = {
  someDate: "2017-05-24"
};

function App() {
  return (
    <div className="App">
      <TextField
        name="someDate"
        label="Some Date"
        InputLabelProps={{ shrink: true, required: true }}
        type="date"
        defaultValue={values.someDate}
      />
    </div>
  );
}

However, when I try to use the current date using a date object

const values = {
  someDate: new Date()
};

I get an error

Warning: Failed prop type: Invalid prop `defaultValue` supplied to `TextField`.

How do I pass a Date to the TextField?

As you can read in the docs defaultValue has to be either a string or a number . The Date type is not supported.

But since you're using type="date" you should be fine by handing the date as string.

eg

const values = {
  someDate: new Date().toISOString().substring(0, 10);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM