在 TextField type=time 材质 ui 中设置默认选取时间

发布于 2025-01-12 19:08:31 字数 256 浏览 4 评论 0原文

我想将默认时间设置为 Material UI 的文本字段类型时间。 我的要求是,在点击选择器之前,没有设置时间,但是点击时,显示08:00作为默认的选择时间。

点击之前

点击后

I would like to set a default time to a textfield type time of Material UI.
My requeriment is that before clicking the picker, no time have been settted up, but when clicking, appears 08:00 as the default time to pick.

Before clicking

After clicking

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

又爬满兰若 2025-01-19 19:08:31

通过给它一个设置为状态的,将您的TextField变成一个受控组件,并更新它onChange

该 API 没有焦点或点击处理程序属性,但是您可以用 span 包装 TextField 并在其上设置点击处理程序。

从那里,创建一个函数,如果事件目标中没有值,则将状态更新为字符串值“08:00”。这将允许您以很少的开销重用 onClickonChange 的函数。

const [time, setTime] = useState("")

const changeTime = (e) => {
  setTime(e.target.value || "08:00")
}

<span onClick={changeTime}>
  <TextField value={time} type="time" onChange={changeTime}/>
</span>

onClick 之所以有效,是因为事件冒泡。您将单击输入,但这会冒泡到跨度的事件侦听器。不应该有机会单击跨度,因为它将适合内容,并且输入将覆盖在其上。

Turn your TextField into a controlled component, by giving it a value that is set to state, and update it onChange.

There are no focus or click handler props for that API, but you can wrap the TextField with a span and set a click handler on that.

From there, create a function to update the state to be a string value of "08:00" if there is no value in the event target. This will allow you to reuse the function for onClick and onChange with little overhead.

const [time, setTime] = useState("")

const changeTime = (e) => {
  setTime(e.target.value || "08:00")
}

<span onClick={changeTime}>
  <TextField value={time} type="time" onChange={changeTime}/>
</span>

The onClick works because of event bubbling. You will be clicking the input, but that bubbles up to the span's event listener. There should be no chance of clicking on the span, because it will fit the content, and input will lay over it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文