0

我正在尝试按照https://v2.grommet.io/form上的示例使用 Grommet 创建一个基本表单。我的具体表格如下所示:

import React from 'react';
import { Box, Form, FormField, TextInput, Button } from 'grommet';

const defaultValue = {};

const LoginForm = () => {
  const [value, setValue] = React.useState(defaultValue);

  function handleSubmit(e) {
    e.preventDefault();
    const { email, password } = e.value;
    console.log('pretending to log in:', email, password);
    // doLogin(email, password)
  }

  return (
    <Form
      value={value}
      onChange={nextValue => {
        setValue(nextValue);
      }}
      onReset={() => setValue(defaultValue)}
      onSubmit={handleSubmit}
    >
      <FormField label="email" name="email" required>
        <TextInput name="email" />
      </FormField>
      <FormField label="password" name="password" required>
        <TextInput name="password" />
      </FormField>
      <Box direction="row" justify="between" margin={{ top: 'medium' }}>
        <Button type="reset" label="Reset" />
        <Button type="submit" label="Login" primary />
      </Box>
    </Form>
  );
};

一旦我开始在任一字段中输入内容,我就会得到以下信息:

Warning: A component is changing an uncontrolled input of type undefined to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: ...

请注意,如果我用上面链接示例中的剪切/粘贴替换我的表单代码,我会得到完全相同的错误。

我对错误的含义有相当合理的理解,但我不知道在这种情况下如何修复它。Grommet 的受控表单组件的实现是否损坏,或者我是否在我的配置或包中的其他地方遗漏了可能导致这种情况的东西?

4

1 回答 1

1

React.js 控制的标准不允许对象未定义。因此,问题从您如何定义您的 开始defaultValue = {};,因为它是一个空对象,因此 FormField 子项没有初始值,这会导致它们未定义,从而导致错误。因此,如果您将预设值更改为更适合您的字段,例如defaultValue = { password: '' };它将修复您的错误。

有关 React 受控和不受控输入的更多阅读,请阅读此A 组件正在将文本类型的不受控输入更改为 ReactJS 中的受控错误

于 2020-07-07T17:49:52.827 回答