如何使用 material-ui-pickers 的日期选择器与 ReactJS 的 State Hook 并将日期传递给父组件?

How to use material-ui-pickers's date picker with ReactJS's State Hook and pass date to the parent component?

我正在尝试使用 material-ui-pickers's date picker, where example demos are written using State Hooks。我想获取日期的值作为对父组件的回调。 这是子组件:

import React, { Component } from 'react';
import { Fragment, useState } from "react";
import { DatePicker, InlineDatePicker } from "material-ui-pickers";

function YearMonthPicker(props) {
const [selectedDate, handleDateChange] = useState("2013-01-01");

  return (
        <div className="picker">
          <DatePicker
            openTo="year"
            views={["year", "month"]}
            label="Year and Month"
            helperText="With min and max"
            minDate={new Date("2011-01-01")}
            maxDate={new Date("2018-12-01")}
            value={selectedDate}
            onChange={handleDateChange}
          />
        </div>
  );
}

export default YearMonthPicker;

在 "onChange" 上,函数修改其 "selectedDate" 状态。

在我的父组件中,我定义了函数:

handleChangeTo = e => {
    this.setState({ dateTo: e.target.value });
};

并且,在渲染方法中,我试图这样调用它:

<YearMonthPicker handleChangeTo={this.handleChangeTo} />

据我了解,如果我将"onChange"的功能更改为props.handleChangeTo,那么子组件的状态将不会在更改时更新。将日期传递给父组件的正确方法是什么?

不是直接使用 handleDataChange 作为 onChange 的处理程序,您可以创建一个新函数,从 props 调用 handleDataChangehandleChangeTohandleChangeTo 然后将直接获取值,而不是事件。

例子

function YearMonthPicker({ handleChangeTo }) {
  const [selectedDate, handleDateChange] = useState("2013-01-01");

  return (
    <div className="picker">
      <DatePicker
        openTo="year"
        views={["year", "month"]}
        label="Year and Month"
        helperText="With min and max"
        minDate={new Date("2011-01-01")}
        maxDate={new Date("2018-12-01")}
        value={selectedDate}
        onChange={val => {
          handleDateChange(val);
          handleChangeTo(val);
        }}
      />
    </div>
  );
}

或者,您可以将此状态保留在父组件中,并将其作为道具传递给 YearMonthPicker,而在子组件中根本没有任何组件状态。