简易搜索框
说明
这只是对于搜索框的简单封装(只有个人使用所需要的功能),不是完整的组件教程
设计
Api
| 参数 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| className | 外加类名 | string | "" |
| style | 外加样式 | object | {} |
| type | input框的类型 | - | - |
| placeholder | 空白填充文字 | string | "" |
| disabled | 是否禁用 | boolean | false |
| 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