Select,value 场景

  1. 有 mode属性,value就是数组
    1. mode 多选模式下,value就是 array
    2. 单选模式下,value就是 string,number, undefined
  2. labelInValue属性
    1. antd 4x:value就是对象 {value: ‘’, label: ‘’}
    2. antd 3x:value就是对象 {key: ‘’, label: ‘’}

Select.js

options 数组渲染 Select

  1. 支持模糊搜索
  2. 支持清除 ```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); } });

  1. let result = [];
  2. if(isFunction(render)) {
  3. result = render(res);
  4. } else {
  5. // 返回的数据是否带分页
  6. result = dataKey ? res[dataKey] : res;
  7. }
  8. if (isArray(result)) {
  9. setOptions(result)
  10. }

}

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

  1. // Select 4x
  2. const value = {value: string, label}
  3. // Select 3x
  4. const value = {key: string, label}

antd Form 3x 使用getFieldDecorator后会让组件变成受控组件,
自动为组件添加 onChange方法和 value属性,从而达到双向绑定

options 数据格式

  1. const options = [
  2. {lalbel: '股票', value: 1},
  3. {lalbel: '期货', value: 2}
  4. ]

在重置表单的时候就可以更新子组件的状态