首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Grommet创建受控窗体会引发错误

使用Grommet创建受控窗体会引发错误
EN

Stack Overflow用户
提问于 2020-05-25 02:07:25
回答 1查看 623关注 0票数 0

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

代码语言:javascript
复制
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>
  );
};

只要我开始在这两个字段中键入内容,就会得到以下结果:

代码语言:javascript
复制
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的受控表单组件的实现被破坏了,还是我的配置或包中缺少了一些可能导致这种情况的东西?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-08 01:49:53

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

有关React受控和非受控输入的更多信息,请阅读此A component is changing an uncontrolled input of type text to be controlled error in ReactJS

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61990216

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档