📜  React Rebass 表单标签组件(1)

📅  最后修改于: 2023-12-03 15:19:44.317000             🧑  作者: Mango

React Rebass 表单标签组件

React Rebass是基于 React 的 UI 组件库,提供了一些默认的样式和组件,方便快速开发页面。其中,表单标签组件提供了一些常用的表单元素,可以大大简化开发者的工作。

安装

使用 npm 安装:

npm install rebass
使用

引入样式文件:

import { Label, Input, Textarea, Select } from 'rebass'

组件使用如下:

<Label htmlFor='input'>输入框</Label>
<Input id='input' name='input' />

<Label htmlFor='textarea'>文本框</Label>
<Textarea id='textarea' name='textarea' />

<Label htmlFor='select'>下拉框</Label>
<Select id='select' name='select'>
  <option value='option1'>选项1</option>
  <option value='option2'>选项2</option>
  <option value='option3'>选项3</option>
</Select>
属性

|属性名|类型|描述| |---|---|---| |htmlFor|string|for 属性的替代,指定标签的 id| |id|string|标签的唯一标识| |name|string|表单元素的名称,用于提交表单| |defaultValue|string/number/boolean|array|表单元素的默认值| |value|string/number/boolean|array|表单元素的值| |disabled|boolean|禁用表单元素| |onChange|function|表单元素值改变时触发的回调函数|

示例
import React, { useState } from 'react'
import { Label, Input, Textarea, Select, Button } from 'rebass'

function Form() {
  const [inputValue, setInputValue] = useState('')
  const [textareaValue, setTextareaValue] = useState('')
  const [selectValue, setSelectValue] = useState('')

  const handleSubmit = e => {
    e.preventDefault()
    console.log('提交了表单')
  }

  return (
    <form onSubmit={handleSubmit}>
      <Label htmlFor='input'>输入框</Label>
      <Input
        id='input'
        name='input'
        value={inputValue}
        onChange={e => setInputValue(e.target.value)}
      />

      <Label htmlFor='textarea'>文本框</Label>
      <Textarea
        id='textarea'
        name='textarea'
        value={textareaValue}
        onChange={e => setTextareaValue(e.target.value)}
      />

      <Label htmlFor='select'>下拉框</Label>
      <Select
        id='select'
        name='select'
        value={selectValue}
        onChange={e => setSelectValue(e.target.value)}
      >
        <option value='option1'>选项1</option>
        <option value='option2'>选项2</option>
        <option value='option3'>选项3</option>
      </Select>

      <Button type='submit'>提交</Button>
    </form>
  )
}

这个示例演示了如何使用 React Rebass 的表单标签组件,包括输入框、文本框、下拉框和按钮。使用 useState 定义表单元素的值,并在 onChange 事件中更新。使用 onSubmit 事件处理表单的提交。