简体   繁体   English

REACT-如何在默认情况下将结束日期设置为与开始日期相同但控制结束日期是否不早于开始日期?

[英]REACT- How to set enddate same as startdate by default but control if enddate not before startdate?

if a user select a starting date, by default I would like that this selection would be the same for the ending date.如果用户选择开始日期,默认情况下我希望此选择与结束日期相同。 And then if the user wants to change this ending date, he can.然后,如果用户想要更改此结束日期,他可以。 For now, I can select the starting date and the ending date.现在,我可以选择开始日期和结束日期。

And putting a condition on my date ie not able to put an ending date that is before a starting date.并在我的日期设置条件,即不能将结束日期设置在开始日期之前。

Here is my code :这是我的代码:

export default function SelectionChoice({ next, selChoice2, setSelChoice2 }) {
  const [summary, setSummary] = useState("");
  const [start, setStart] = useState("");
  const [end, setEnd] = useState("");
  const [selChoice1, setSelChoice1] = useState();
  const [data, setData] = useState([])


  useEffect(() => {
    myApi.functionA()
      .then((res) => {
        console.log(res);
        setData(res.data.data);
      })
      .catch((err) => {
        console.log(err);
      });
  }, []);

  ...
  const choice1 = data?.map((item) => {
    return {
      label: item.name,
      value: item.id
    };
  });

  const choice2 = data?.flatMap((item) => {
    return item.choice2.map((c) => ({
      label: c.name,
      value: c.id
    }));
  });

  const textChange = (e) => {
    if (e?.target?.id === undefined) return setSelChoice1(e);
    if (e?.target?.id === undefined) return setSelChoice2(e);
    switch (e.target.id) {    
    ...
      case "start":
        setStart(e.target.value);
        break;
      case "end":
        setEnd(e.target.value);
        break;
      default:
    }
  };
  return (
    <>
      <form>
        <div >
          Choose choice1 and choice2
        </div>
        <div>
          <label>
            Choice1:
            <CustomDropdown
              options={choice1}
              value={selChoice1}
              setValue={setSelChoice1}
              isMulti={true}
            />
          </label>
          <label>
            Choice2:
            <CustomDropdown
              options={choice2}
              value={selChoice2}
              setValue={setSelChoice2}
              isMulti={true}
            />
          </label>
        </div>
        <div>
          <label>
            Start:
            <div>
              <input
                type="date"
                name="start"
                value={start}
                onChange={textChange}
                id="start"
              />
            </div>
          </label>
          <label>
            End:
            <div>
              <input
                type="date"
                name="end"
                value={end}
                onChange={textChange}
                id="end"
              />
            </div>
          </label>
          <p className="formfield">
            <label
              for="summary"
            >
              Description :
              <textarea
                value={summary}
                onChange={textChange}
                name="summary"
                id="summary"
                cols="10"
                rows="10"
              />
            </label>
          </p>
        </div>
      </form>
        <button
          onClick={() =>
            next({           
              ...,
              start,
              end
            })
          }
        >
          Next
        </button>
    </>
  );
}

You can check if the end date is having any value while updating the start date and set it if it is not having any value.您可以在更新开始日期时检查结束日期是否有任何值,如果没有任何值则设置它。

switch (e.target.id) {
  case "start":
    setStart(e.target.value);
    if (!end) {
      setEnd(e.target.value);
    }
    break;
  case "end":
    if (e.target.value >= start) {
      setEnd(e.target.value);
    } else {
      //flash error message
    }
    break;
  default:
}

I would like you update the code like below for checking possible cases.我希望您更新如下代码以检查可能的情况。 And I also updated the Async Function with async/await.我还用 async/await 更新了异步函数。

export default function SelectionChoice({ next, selChoice2, setSelChoice2 }) {
  ...
  const [start, setStart] = useState("");
  const [end, setEnd] = useState("");
  ...

  useEffect(() => {
    /*
    myApi.functionA()
      .then((res) => {
        console.log(res);
        setData(res.data.data);
      })
      .catch((err) => {
        console.log(err);
      });
      */

    const getData = async () => {
      try {
        const res = await myApi.functionA();
        setData(res.data.data);
      } catch(err) {
        console.log(err)
      }
    }

    getData();

  }, []);

  const textChange = (e) => {
    switch (e.target.id) {    
      case "start":
        setStart(e.target.value);
        const startDate = new Date(e.target.value).getTime();
        const endDate = new Date(end).getTime();

        // Check if end date is not set 
        // Or End Date is before Start Date
        if (!!end || startDate > endDate) {
          setEnd(e.target.value)
        }
    
        break;
      case "end":
        const endDate = new Date(e.target.value).getTime();
        const startDate = new Date(start).getTime();

        // Check End Date is before the Start Date
        if (endDate < startDate) {
           setEnd(start);
        } else {
           setEnd(e.target.value);
        }
      
        break;
      default:
        break;
    }
  };

  return (
    ...
  )

Hope this would help you even a little.希望这会对您有所帮助。

Thanks谢谢

请注意您的结束日期不要早于您的开始日期

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果使用react在prevstartdate之前设置startdate,如何将enddate设置为null? - How to set enddate to null if startdate is set before prevstartdate using react? 为 react-dates 设置默认的 startDate 和 endDate 属性 - Setting the default startDate and endDate properties for react-dates react-dates onDatesChange startDate 和 endDate 是 null, DayPickerRangeController - react-dates onDatesChange startDate and endDate are null, DayPickerRangeController 使用react-jsonschema-form将开始日期和结束日期转换为Unix时间 - Convert startdate and enddate to unix time with react-jsonschema-form 除了标题,开始日期,结束日期之外,如何在反应调度程序中显示其他数据,例如位置和会议成员? - How to display additional data like location and members of the meeting in the react scheduler apart from title, startDate,endDate? 如何从ANTD.DESIGN的RangePicker获取startDate和endDate - How To Get startDate and endDate from RangePicker from ANTD.DESIGN react-dates DayPickerRangeController,如果用户在已选择时单击它,是否有办法清除 startDate 或 endDate? - react-dates DayPickerRangeController, is there a way to clean startDate or endDate if user clicks it when already selected? onClose,react-date-presets 在选择范围时返回未定义的 startDate,endDate。 好的,如果 select 自定义范围 - onClose, react-date-presets returns undefined startDate, endDate, when pick a range. OK if select custom-range Moment.js - 如何获取给定月份的每周数据[每周的开始日期和结束日期],不包括上个月和下个月的日期 - Moment.js - How to get weekly data [startDate & endDate of each week] for given month excluding previous and next month date 需要使用 Reactjs 从 startDate 开始执行 endDate 不能超过一年 - Need to implement endDate cannot be more than one year from startDate using Reactjs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM