简体   繁体   English

如何在 Material-UI TextField 中设置当前日期

[英]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.如果我在TextField上设置type="date"我可以用字符串初始化它。

https://codesandbox.io/s/9y6yz462op 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?如何将日期传递给 TextField?

As you can read in the docs defaultValue has to be either a string or a number .正如您在文档中所读到的那样defaultValue必须是stringnumber The Date type is not supported.不支持Date类型。

But since you're using type="date" you should be fine by handing the date as string.但是由于您使用的是type="date" ,因此将日期作为字符串传递应该没问题。

eg例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 material-ui 中为当前日期和时间的文本字段类型 datetime-local 设置默认值? - how can I set the default value to the textfield type datetime-local in material-ui for the current date and time? 如何为 Material-ui TextField Type=date 设置默认日期 - how to set a default date for a Material-ui TextField Type=date ReactJS + Material-UI:如何使用 Material-UI 将当前日期设置为默认值<DatePicker> ? - ReactJS + Material-UI: How to set current date as default value using Material-UI's <DatePicker>? 如何设置React Material-UI所需的TextField样式 - How Do I Style A React Material-UI Required TextField Material-UI中的TextAreaAutoSize组件如何设置宽度? - How do I set a width for the TextAreaAutoSize component in Material-UI? 如何在material-ui的导航栏中设置onClick? - How do I set the onClick in the navbar of material-ui? 设置 TextField 高度 material-ui - Set TextField height material-ui 如何将 material-ui TextField 设置为仅接受十六进制字符 - How can I set material-ui TextField to accept only Hexidecimal characters 如何设置类似于 Material-UI 的轮廓文本字段的 static 轮廓 div? - How can I set an static outlined div similar to Material-UI's outlined textfield? ReactJS - 如何为 material-ui 的文本字段设置值? - ReactJS - How can I set a value for textfield from material-ui?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM