如何在Material-UI文本字段中设置当前日期

时间:2019-04-30 06:36:20

标签: reactjs material-ui

如果在type="date"上设置TextField,则可以使用字符串对其进行初始化。

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>
  );
}

但是,当我尝试使用日期对象使用当前日期时

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

我遇到错误

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

如何将日期传递给文本字段?

1 个答案:

答案 0 :(得分:1)

您可以在the docs中阅读,defaultValue必须是stringnumber。不支持Date类型。

但是,由于您使用的是type="date",因此可以将日期作为字符串传递。

例如

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