【问题标题】: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>
      </>
    );
    

    【讨论】:

      猜你喜欢
      • 2017-08-12
      • 1970-01-01
      • 2013-06-07
      • 2023-01-27
      • 2018-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多