重新渲染擦拭我的输入,如何保留它们?

时间:2020-01-23 22:37:58

标签: reactjs state react-hooks

interface DateRangePickerDialogProps
{
    format:string;
    rangeEnabled:boolean;
    startDate:Date;
    endDate:Date;
    onAccept(startDate:Date, endDate:Date):void;
}


export function DateRangePickerDialog(props: DateRangePickerDialogProps & DialogProps)
{
    const [startDate, setStartDate] = useState(props.startDate);
    const [endDate, setEndDate] = useState(props.endDate);

    const onDateRangeChange = (startDate:Date, endDate:Date) =>
    {
        setStartDate(startDate);
        setEndDate(endDate);
    }

    const onAccept = () =>
    {
        props.onAccept(startDate, endDate);
        props.onHide();
        console.log(startDate, endDate)

    }

    return <Dialog {...props as DialogProps} icon={FiCalendar}>
        <DateRangePicker rangeEnabled={props.rangeEnabled} onDateRangeChange={onDateRangeChange}
            startDate={startDate} endDate={endDate} format={"dd-MMM-yyyy HH:mm:ss"}/>
            <button onClick={() => onDateRangeChange(startDate,endDate)}>Aceptar</button>
        {/* <MainButton className='dialog-button' label='Aceptar' onClick={onAccept} autoFocus={true} /> */}
    </Dialog>;
}

这是我的代码,它几乎可以正常工作,我有一个日历,可以在其中选择“开始”和“结束日期”,但是当我单击日历上的“接受”时,它隐藏了我选择消失的日子。 。有什么想法可以解决此问题并在再次关闭/打开日历后保持日期正确吗?我是钩子的新手...:,(我有点迷路了。enter code here

2 个答案:

答案 0 :(得分:0)

您需要将更改后的值存储在组件的状态中,然后将其设置为输入元素的值。

This article向您展示如何使用Hooks更新输入元素,如下所示:

import React, { useState } from "react";

export function NameForm(props) {
  const [name, setName] = useState("");
  
  const handleSubmit = (evt) => {
      evt.preventDefault();
      alert(`Submitting Name ${name}`)
  }
  return (
    <form onSubmit={handleSubmit}>
      <label>
        Frirst Name:
        <input
          type="text"
          value={name}
          onChange={e => setName(e.target.value)}
        />
      </label>
      <input type="submit" value="Submit" />
    </form>
  );
}

答案 1 :(得分:0)

另一种解决方案是使用MobX之类的状态管理解决方案-https://mobx.js.org/README.html

MobX具有良好且易于学习的曲线,并且非常直观。

简而言之,您可以使用@observable装饰商店中的值:

export class DateRangePickerDialogStore {
    @observable startDate = undefined;
    @observable endDate = undefined;

    @action
    resetStore = () =>< {
        this.startDate = undefined;
        this.endDate = undefined;
    }

    @action
    updateStartDate = value => {
        this.startDate = value;
    }

    @action
    updateEndDate = value => {
        this.endDate = value;
    }
}

和带有@observer的组件:

export const DateRangePickerDialog = observer((props: DateRangePickerDialogProps & DialogProps){

...

})

,然后可以通过调用action或从store变量来从商店中设置和检索值。类似于此的实现将使您存储的值能够保留组件的重新渲染。

希望这会有所帮助:)