无法使用 React 挂钩将 TextField 的状态设置为未定义

Unable to set state of TextField to undefined using React hook

我想将日期 TextField 的初始状态设置为 undefined 直到用户选择日期,然后允许用户轻松地将日期重置回 undefined.

在下面的代码中,重置按钮会正确地将 parameters.count 状态重置为 0,但不会将 parameters.date 重置为 undefinedundefined这种情况有特殊处理吗?

import React, { useState } from "react";
import { Button, TextField } from "@material-ui/core";

import "./App.css";

export type Parameters = {
  count: number;
  date?: string;
};

const initialParameters: Parameters = {
  count: 0,
  date: undefined,
};

export const App: React.FC = () => {
  const [parameters, setParameters] = useState<Parameters>(initialParameters);

  const handleCountChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setParameters({
      ...parameters,
      count: Number(event.target.value),
    });
  };

  const handleDateChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setParameters({
      ...parameters,
      date: event.target.value,
    });
  };

  const resetState = () => {
    setParameters(initialParameters);
  };

  return (
    <div className="App">
      <TextField
        type="number"
        label="Count"
        value={parameters.count}
        onChange={handleCountChange}
      />
      <TextField
        label="Date"
        type="date"
        value={parameters.date}
        onChange={handleDateChange}
        InputLabelProps={{
          shrink: true,
        }}
      />
      <Button onClick={resetState}>Reset</Button>
    </div>
  );
};

基于@cbr 的评论的解决方案是在传递给 TextField.

之前将 undefined 强制转换为 ""
import React, { useState } from "react";
import { Button, TextField } from "@material-ui/core";

import "./App.css";

export type Parameters = {
  count: number;
  date?: string;
};

const initialParameters: Parameters = {
  count: 0,
  date: undefined,
};

export const App: React.FC = () => {
  const [parameters, setParameters] = useState<Parameters>(initialParameters);

  const handleCountChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setParameters({
      ...parameters,
      count: Number(event.target.value),
    });
  };

  const handleDateChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setParameters({
      ...parameters,
      date: event.target.value,
    });
  };

  const resetState = () => {
    setParameters(initialParameters);
  };

  // TextField expects blank string to represent no value.
  const dateDisplay = parameters.date ? parameters.date : "";
  return (
    <div className="App">
      <TextField
        type="number"
        label="Count"
        value={parameters.count}
        onChange={handleCountChange}
      />
      <TextField
        label="Date"
        type="date"
        value={dateDisplay}
        onChange={handleDateChange}
        InputLabelProps={{
          shrink: true,
        }}
      />
      <Button onClick={resetState}>Reset</Button>
    </div>
  );
};