最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to show the date picker if I click the parent div after explictly hiding the date type input in React? - Stack

programmeradmin0浏览0评论

So, I am trying to create a component that will show your typical date picker if an user clicks anywhere in the parent div. But I don't want to show the date type input.

<div className="flex flex-row gap-3">
    <div className="p-3 ... rounded bg-white cursor-pointer">
        <p className="font-normal text-sm ...">{date}</p>
        <input type="date" className="hidden" />
    </div>
    <div>{...}</div>
</div>

So, I am trying to create a component that will show your typical date picker if an user clicks anywhere in the parent div. But I don't want to show the date type input.

<div className="flex flex-row gap-3">
    <div className="p-3 ... rounded bg-white cursor-pointer">
        <p className="font-normal text-sm ...">{date}</p>
        <input type="date" className="hidden" />
    </div>
    <div>{...}</div>
</div>
Share Improve this question asked Feb 3 at 17:18 GukkeyGukkey 711 silver badge10 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 3

You can open the picker menu of individual input fields with the showPicker() method using an external event.

  • HTMLInputElement: showPicker() method - MDN Docs

Note: Pickers for date, datetime-local, month, time, week are launched in the same way. They cannot be shown here because live examples run in a cross-origin frame, and would cause a SecurityError

This does not work in an iframe or in the StackOverflow CodeSnippet! Create your own reproduction based on the code. I have attached the result in the image.

If you hide the date input field (display: none;), it won't be able to calculate its current position. Instead, make the parent div relative. Position the input in the bottom left corner, and set its height and width to 0.

<script src="https://cdnjs.cloudflare/ajax/libs/react/18.3.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare/ajax/libs/react-dom/18.3.1/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare/ajax/libs/babel-standalone/7.25.6/babel.min.js"></script>
<script src="https://unpkg/@tailwindcss/browser@4"></script>

<div id="root"></div>

<script type="text/babel" data-presets="env,react">
const { useState, useRef } = React;

function DatePickerComponent() {
  const [date, setDate] = useState("");
  const inputRef = useRef(null);

  const handleDateOverlay = () => {
    inputRef.current?.showPicker();
  };

  const handleDateChange = (e) => {
    setDate(e.target.value);
  };

  return (
    <div className="space-x-4 p-4">
      <div
        class="relative cursor-pointer"
        onClick={handleDateOverlay}
      >
        <span className="text-3xl">

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论