使用 Premium Chakra UI 组件更快地构建 💎

了解更多
跳到内容
文档演练场指南博客
赞助

Field

用于为表单字段添加标签、帮助文本和错误消息。

源码Storybook配方Ark

用法

import { Field } from "@chakra-ui/react"
<Field.Root>
  <Field.Label>
    <Field.RequiredIndicator />
  </Field.Label>
  <Input />
  <Field.HelperText />
  <Field.ErrorText />
</Field.Root>
信息
如果您更喜欢封闭组件组合,请查看下方代码片段

示例

错误文本

invalid 属性传递给 Field.Root,并使用 Field.ErrorText 来指示字段无效。

这是一条错误文本

帮助文本

使用 Field.HelperText 为字段添加帮助文本。

这是一条帮助文本

水平排列

使用 orientation="horizontal" 属性可水平对齐标签和输入框。

禁用

使用 disabled 属性可禁用该字段。

文本域

以下是 Field 组件与文本域的用法。

原生选择框

以下是 Field 组件与原生选择框的用法。

必填

required 属性传递给 Field.Root,并使用 Field.RequiredIndicator 来指示字段是必填的。

可选

fallback 属性传递给 Field.RequiredIndicator 以添加可选文本。

封闭组件

以下是为封闭组件组合设置 Field 的方法。

import { Field as ChakraField } from "@chakra-ui/react"
import * as React from "react"

export interface FieldProps extends Omit<ChakraField.RootProps, "label"> {
  label?: React.ReactNode
  helperText?: React.ReactNode
  errorText?: React.ReactNode
  optionalText?: React.ReactNode
}

export const Field = React.forwardRef<HTMLDivElement, FieldProps>(
  function Field(props, ref) {
    const { label, children, helperText, errorText, optionalText, ...rest } =
      props
    return (
      <ChakraField.Root ref={ref} {...rest}>
        {label && (
          <ChakraField.Label>
            {label}
            <ChakraField.RequiredIndicator fallback={optionalText} />
          </ChakraField.Label>
        )}
        {children}
        {helperText && (
          <ChakraField.HelperText>{helperText}</ChakraField.HelperText>
        )}
        {errorText && (
          <ChakraField.ErrorText>{errorText}</ChakraField.ErrorText>
        )}
      </ChakraField.Root>
    )
  },
)

如果您想自动将封闭组件添加到您的项目中,请运行该命令

npx @chakra-ui/cli snippet add field

属性

Root

属性默认值类型
colorPalette 'gray'
'gray' | 'red' | 'orange' | 'yellow' | 'green' | 'teal' | 'blue' | 'cyan' | 'purple' | 'pink'

组件的调色板

orientation 'vertical'
'vertical' | 'horizontal'

组件的方向

asChild
boolean

使用提供的子元素作为默认渲染元素,结合它们的属性和行为。

更多详情,请阅读我们的 组合 指南。
disabled
boolean

指示字段是否被禁用。

ids
ElementIds

字段部分的ID。

invalid
boolean

指示字段是否无效。

readOnly
boolean

指示字段是否只读。

required
boolean

指示字段是否为必填项。

as
React.ElementType

要渲染的底层元素。

unstyled
boolean

是否移除组件的样式。

上一页

空状态

下一页

Fieldset