【问题标题】:React material UI open datepicker on button clickReact Material UI 在按钮点击时打开日期选择器
【发布时间】:2023-01-31 21:08:09
【问题描述】:
我正在为 Datepicker 使用反应材料 ui。
<TextField
id="datetime-local"
label="Next appointment"
type="datetime-local"
defaultValue="2017-05-24T10:30"
sx={{ width: 250 }}
InputLabelProps={{
shrink: true,
}}
/>
我想点击一个按钮打开这个日期选择器。
提前致谢。
【问题讨论】:
标签:
javascript
reactjs
ecmascript-6
material-ui
【解决方案1】:
您可以通过在 HTMLInputElement 上使用 showPicker 函数来实现这一点。
为本机输入元素创建一个 ref。您可以使用 inputProps 将 ref 向下传递到输入。
const inputRef = useRef(null);
const handleClick = () => {
// check if the ref is set
if (inputRef.current === null) return;
inputRef.current.showPicker();
};
return (
<>
<TextField
id="datetime-local"
label="Next appointment"
type="datetime-local"
defaultValue="2017-05-24T10:30"
sx={{ width: 250 }}
inputProps={{
ref: inputRef,
}}
InputLabelProps={{
shrink: true,
}}
/>
<button onClick={handleClick}>open datepicker</button>
</>
);