React with Fluent UI Form onChange 不起作用(非常简单的代码)

React with Fluent UI Form onChange not working (very simple code)

我正在使用 ReactFluentUI 构建一个简单的表单,代码如下

import React, { useState, FormEvent } from "react";

import { PrimaryButton } from "office-ui-fabric-react/lib/Button";

import { IUserFormValues } from "../../models/user";
import { Stack, TextField } from "@fluentui/react";

const NewUIForm = () => {
  const [user, setUser] = useState<IUserFormValues>({
    email: "",
    password: "",
  });

  const handleInputChange = (
    event: FormEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => {
    const { name, value } = event.currentTarget;
    setUser({ ...user, [name]: value });
  };

  const log123 = () => {
    console.log(user.email);
  };

  return (
    <Stack>
      <Stack>
        <Stack.Item grow>
          <TextField
            placeholder="UserName"
            label="User Name"
            value={user.email}
            name="email"
            onChange={handleInputChange}
          />
          <TextField
            placeholder="Password"
            label="Password"
            value={user.password}
            name="password"
            onChange={handleInputChange}
          />
        </Stack.Item>
        <PrimaryButton onClick={log123}>Add</PrimaryButton>
      </Stack>
    </Stack>
  );
};
export default NewUIForm;

每次我在 TextField 中输入内容时都会出现此错误

TypeError: Cannot destructure property 'name' of 'event.currentTarget' as it is null.

有人可以帮助我吗?谢谢!!

流畅 UI onChange 函数需要两个参数:事件和值(可选)

(event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>, newValue?: string) => void

https://developer.microsoft.com/en-us/fluentui#/controls/web/textfield#implementation

您可以像这样更改 handleInputChange 函数:

  const handleInputChange = (
    event: { target: HTMLInputElement },
    newValue:String
  ):void => {
    const { name } = event.target;
    setUser({ ...user, [name]: newValue });
  };

您可以从 here

检查此工作 fiddle