首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >FormField中的自定义组件

FormField中的自定义组件
EN

Stack Overflow用户
提问于 2021-05-12 23:54:08
回答 1查看 484关注 0票数 1

在Grommet FormField文档中,它在组件下面声明;

只要组件支持名称、值、onChange (事件=> {})的属性,而事件具有event.value或event.target.value,则组件可能是自定义的。

我想实现一个自定义组件,但不明白它需要如何与受控的Form组件交互才能提供其value属性。是否有示例说明如何在FormField中实现自定义组件?

EN

回答 1

Stack Overflow用户

发布于 2021-05-14 23:20:54

下面是一个使用自定义输入组件的受控表单代码示例。我使用了一个普通的输入标记,因为它支持上述docs规范。

...it支持名称、值、onChange (事件=> {})的属性,而事件具有event.value或event.target.value。

但是,您可以使用下面的模板示例使用自己的输入组件实现。输入的值将传递给受控表单,而不需要额外的编码。运行以下是并签出控制台日志,查看在输入自定义输入时如何更新该值。

代码语言:javascript
复制
import React, { useState } from "react";
import { render } from "react-dom";

import { Box, Button, Form, FormField, Grommet, TextInput } from "grommet";
import { grommet } from "grommet/themes";

const defaultValue = {
  name: "",
  custom: ""
};

export const App = () => {
  const [value, setValue] = useState(defaultValue);
  return (
    <Grommet full theme={grommet}>
      <Box fill align="center" justify="center">
        <Box width="medium">
          <Form
            value={value}
            onChange={(nextValue, { touched }) => {
              console.log("Change", nextValue, touched);
              setValue(nextValue);
            }}
            onSubmit={(event) =>
              console.log("Submit", event.value, event.touched)
            }
          >
            <FormField label="TextInput Field" name="name">
              <TextInput name="name" />
            </FormField>
            <FormField
              label="Custom Component Field"
              name="custom"
              component={(props) => <input {...props} />} // custom component
            />

            <Box direction="row" justify="between" margin={{ top: "medium" }}>
              <Button type="submit" label="Update" primary />
            </Box>
          </Form>
        </Box>
      </Box>
    </Grommet>
  );
};

render(<App />, document.getElementById("root"));
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67512344

复制
相关文章

相似问题

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