Select,value 场景
- 有 mode属性,value就是数组
- mode 多选模式下,value就是 array
- 单选模式下,value就是 string,number, undefined
- labelInValue属性
- antd 4x:value就是对象 {value: ‘’, label: ‘’}
- antd 3x:value就是对象 {key: ‘’, label: ‘’}
Select.js
options 数组渲染 Select
- 支持模糊搜索
- 支持清除 ```tsx import React, { useState, useEffect, forwardRef, memo } from ‘react’; import { array, func, object, string } from ‘prop-types’; import { Select as AntdSelect } from ‘antd’; import { useRequest } from ‘ahooks’; import { toLower, isEmpty, isArray, isFunction, isEqual, noop, merge } from ‘lodash-es’;
const SelectRef = forwardRef(Select);
SelectRef.propTypes = { options: array, onChange: func, request: func, // 请求的方法 Promise payload: object, // 请求的参数 placeholder: string, dataKey: string, // 带分页数据 res.data render: func, };
SelectRef.defaultProps = { onChange: noop, placeholder: ‘请选择’, }
export default SelectRef;
function Select(props, ref) { const { value, onChange, options: data, defaultOptions, request, payload, render, dataKey, …rest } = props; const [selected, setSelected] = useState(); const [options, setOptions] = useState([]);
const { loading, runAsync } = useRequest(request, merge(requestOptions));
// 如果有 request就是远程请求获取数据 useEffect(() => { // 如果传入了 options就不要请求 if (!isEmpty(data) && isArray(data)) { return; } init(); }, [payload]);
useEffect(() => { if (isEqual(value, selected)) return; setSelected(value); }, [value]);
async function init() { const res = await runAsync(merge(payload)) .catch((e) => { // 如果设置了默认值 if (isArray(defaultOptions)) { setOptions(defaultOptions); } });
let result = [];
if(isFunction(render)) {
result = render(res);
} else {
// 返回的数据是否带分页
result = dataKey ? res[dataKey] : res;
}
if (isArray(result)) {
setOptions(result)
}
}
function handleChange(value, option) { setSelected(value); onChange(value, option); }
/**
- Select 模糊搜索
- @param input {string} 输入的字符串
- @param option {object} options的配置项
@returns {boolean} */ function filterOption(input, option) { const _key = rest.fieldNames?.label ?? ‘label’; return toLower(option[_key]).includes(toLower(input)); }
return (
); } ```
Select细节
labelInValue
Select 4x的 labelInValue和 antd 3x的对象格式区别,key, value
// Select 4x
const value = {value: string, label}
// Select 3x
const value = {key: string, label}
antd Form 3x 使用getFieldDecorator后会让组件变成受控组件,
自动为组件添加 onChange方法和 value属性,从而达到双向绑定
options 数据格式
const options = [
{lalbel: '股票', value: 1},
{lalbel: '期货', value: 2}
]
在重置表单的时候就可以更新子组件的状态