antd select onChange识别不同OptGroup解决方案

1,374 阅读1分钟

背景: 数组对象数据结构中,前端可以根据不同的对象属性进行筛选想要的数据 方案一 (react hook): 在Option value属性上添加 不同OptGroup的key值(${LABEL}_) ,在filterFormFieldList 方法中进行过滤,根据不同的key 去查对应的数据 UI

  return (
    <>
      <Select
        showSearch
        style={{ width: 230, marginBottom: 15 }}
        placeholder="输入字段的名称/key/类型"
        optionFilterProp="children"
        value={searchValue}
        onChange={handleChange}
        allowClear
      >
        <OptGroup label="字段名称">
          {uniqBy(formFieldList, LABEL).map((val) => {
            return <Option value={`${LABEL}_` + val.label}>{val.label}</Option>
          })}
        </OptGroup>
        <OptGroup label="字段key">
          {uniqBy(formFieldList, MODEL).map((val) => {
            return <Option value={`${MODEL}_` + val.model}>{val.model}</Option>
          })}
        </OptGroup>
        <OptGroup label="字段类型">
          {uniqBy(formFieldList, VALUE_TYPE).map((val) => {
            return <Option value={`${VALUE_TYPE}_` + val.valueType}>{val.valueType}</Option>
          })}
        </OptGroup>
      </Select>
      <Table className="table" rowKey={(record, i) => record.index} columns={formFieldsColumns} dataSource={filterFormFieldList} bordered />
    </>
  )

核心代码

  const [searchValue, setSearchValue] = useState(undefined)
  let formFieldList = formatFormFieldList(formContent, appDetail)

  const handleChange = (value, option) => {
    setSearchValue(value)
  }

  const filterFormFieldList = useMemo(() => {
    return formFieldList.filter((value) => {
      if (searchValue && searchValue !== '') {
        const type = searchValue.split('_').shift()
        let newValue = searchValue.replace(type + '_', '')
        return value[type] === newValue
      }
      return true
    })
  }, [searchValue, formFieldList])