Liuqing650/blog

[ant-design问题记录]Select的使用方式

Closed this issue · 0 comments

使用 Ant-design 组件的 Select 时, Option 通常是一个遍历函数

import { Select } from 'antd';

const Option = Select.Option;

const createOptions = (options) => {
 if (!options || options.length === 0) {
      // null or undefined
      return undefined; 
    }
    return options.map(opt => (<Option key={opt}>{opt}</Option>));
};
const mode = 'multiple';
// undefined 和 null 是完全不同的,null不显示 placeholder
const defaultValue = undefined;
return (
  <Select mode={mode} defaultValue={defaultValue}>
    {createOptions(options)}
  </Select>
)

关于 notFoundContent 可变时的处理方式

notFoundContent 接收的是一个 elm 节点或者 string

createNotFoundContent = (item) => {
  if (item.loading) {
    return <Spin size="small" />
  }
  return item.notFoundContent || '没有匹配结果';
}
// createNotFoundContent函数 如果直接放到 notFoundContent 中执行会报警告
// Warning: Functions are not valid as a React child. 
const notFoundContent = createNotFoundContent(item);
return (
  <Select notFoundContent={notFoundContent}>
    {createOptions(options)}
  </Select>
)