React简易搜索框

205 阅读1分钟

简易搜索框

说明

这只是对于搜索框的简单封装(只有个人使用所需要的功能),不是完整的组件教程

设计

Api

参数说明类型默认值
className外加类名string""
style外加样式object{}
typeinput框的类型--
placeholder空白填充文字string""
disabled是否禁用booleanfalse
onChange输入框内容改变时执行(参数是改变后的值)EventChange-

代码

type Props = {
  className?: string
  style?: object

  type?: string
  placeholder?: string
  disabled?: boolean

  onChange?: (str: string) => void
}

const Search = ({
  className = '',
  style = {},

  type = 'text',
  placeholder = '请输入值:',
  disabled = false,

  onChange = (str) => {},
}: Props) => {
    // 存储值(受控组件)
  const [value, setValue] = useState<string>('')
  // 设为防抖函数
  const afterChange = useDebounce(onChange, 400)
  // 改变存储的值
  const change = (e: ChangeEvent) => {
    const val = (e.currentTarget as HTMLInputElement).value
    setValue(val)
    afterChange(val)
  }
return (
    <div className={`${styles.search}`} style={style}>
      <input
        className={`${styles.ipt} ${className}`}
        style={style}
        type={type}
        value={value}
        placeholder={placeholder}
        disabled={disabled}
        onChange={change}
      />
    </div>
  )
}

使用

import React from 'react'
import Search from '../../UI/Search/Search'

const TestSearch = () => {
  return (
    <div>
      <Search></Search>
    </div>
  )
}

export default TestSearch