仅在选择选项时如何显示日期选择器?

时间:2020-10-05 18:57:08

标签: javascript html css reactjs datepicker

我正在使用react-datepicker并具有一个带有4个选项的select,仅在选择选项3时才需要显示日历。这是我到目前为止的代码。

const [startDate, setStartDate] = useState(new Date())

 <div className="input-block">
   <label htmlFor="status">Status</label>
   <select id="status" name="status" required>
     <option value="1">Aguardando Disponibilidade</option>
     <option value="2">Aguardando Agendamento</option>
     <option value="3">Ativação Agendada</option>
     <option value="4">Ativação Efetuada</option>
   </select>

   <div className="calendar">
     <DatePicker
       className="calendar-input"
       selected={startDate}
       onChange={(date) => setStartDate(date)}
       showTimeSelect
       timeFormat="HH:mm"
       dateFormat="dd/MM/yyyy HH:mm "
      />
   </div>
</div>

1 个答案:

答案 0 :(得分:0)

import React, { useState } from 'react';

const YourComp = () => {
  const [selectedValue, updateSelectedValue] = useState();
  const [startDate, setStartDate] = useState(new Date())

  const onSelectChange = ({ target: { value } }) => updateSelectedValue(value);

  return (
    <div className="input-block">
     <label htmlFor="status">Status</label>
     <select
      id="status"
      name="status"
      required
      onChange={onSelectChange}
     >
       <option value="1">Aguardando Disponibilidade</option>
       <option value="2">Aguardando Agendamento</option>
       <option value="3">Ativação Agendada</option>
       <option value="4">Ativação Efetuada</option>
     </select>
   {
     selectedValue === '3'
     ? (
      <div className="calendar">
        <DatePicker
         className="calendar-input"
         selected={startDate}
         onChange={(date) => setStartDate(date)}
         showTimeSelect
         timeFormat="HH:mm"
         dateFormat="dd/MM/yyyy HH:mm "
        />
      </div>
     )
     : null
   }
</div>
  )
}

上述代码可以解决您的问题。这个想法是要进行条件检查以呈现DatePicker组件。 React Official Doc - Conditional Rendering