无法使用React钩子将TextField的状态设置为undefined

时间:2020-10-07 16:57:51

标签: reactjs typescript material-ui react-hooks react-state-management

我希望将日期 private final Student student; private final Set<SelectExpression> SELECT_ROWS = new HashSet<>(); public Set<SelectExpression> retrieveSubjects() { for (Year year : student.getYear()) { SELECT_ROWS.add(new SelectExpression( sub.getMajor(), sub.getMinor() )); } return SELECT_ROWS; } 的初始状态设置为TextField,直到用户选择了一个日期,然后允许用户轻松地将日期重置为{{1 }}。

在以下代码中,“重置”按钮会将undefined状态正确重置为undefined,但不会将parameters.count重置为0。在这种情况下,parameters.date是否得到了特殊待遇?

undefined

1 个答案:

答案 0 :(得分:1)

基于@cbr的评论的解决方案是在传递给undefined之前将""强制为TextField

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>
  );
};