You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+Ant Design Select根据数据库类型配置自定义图标颜色

Solution: Add Type-Colored Icons to Ant Design Select Options

Got it, let's work through this together! You're already on the right track mapping your dbConfigList to Options—we just need to extend that to include a colored icon based on the type field in each item's data property. Here's a step-by-step fix:

Step 1: Parse the data JSON string

Your data field is stored as a JSON string, so first we need to convert it back to an object to access the type value. We'll use JSON.parse() for this (add a try/catch if you want to handle invalid JSON, but your sample data looks valid).

Step 2: Create a color mapping for each type

Define a simple object that maps each database type to its corresponding color—this makes it easy to look up the color later without repeating code.

Step 3: Customize the Option content

Instead of just showing dbConfig.name, we'll combine an icon (using Ant Design's built-in icons) with the name, and set the icon's color based on the parsed type.

Full Updated Code

import { Form, Select, Icon } from 'antd';
// For Ant Design v4+, import icons like this instead:
// import { DatabaseOutlined } from '@ant-design/icons';

const { Option } = Select;

class YourComponent extends React.Component {
  // ... your existing state and methods (like onConfigNameChange)

  render() {
    // Color mapping for each database type
    const typeColorMap = {
      elastic: '#9254de', // Purple
      mysql: '#52c41a', // Green
      mongo: '#8c8c8c' // Gray
    };

    const { getFieldDecorator } = this.props.form;
    return (
      <Form.Item label="Choose Configuration">
        {getFieldDecorator('select', {
          valuePropName: 'value', // Note: Ant Design Select uses 'value' as the prop name, not 'option'—this was likely a typo!
          rules: [{ required: true, message: 'Please select a configuration' }],
          onChange: (value) => { this.onConfigNameChange(value) },
        })(
          <Select mode="single" placeholder="Please select Configuration">
            {this.state.dbConfigList.map((dbConfig) => {
              // Parse the data string to extract the type
              const parsedData = JSON.parse(dbConfig.data);
              // Get the matching color, default to gray if type isn't in our map
              const iconColor = typeColorMap[parsedData.type] || '#8c8c8c';

              return (
                <Option key={dbConfig.id} value={JSON.stringify(dbConfig)}>
                  {/* Use flex to align icon and text neatly */}
                  <span style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                    {/* For Ant Design v3: */}
                    <Icon type="database" style={{ color: iconColor }} />
                    {/* For Ant Design v4+: */}
                    {/* <DatabaseOutlined style={{ color: iconColor }} /> */}
                    <span>{dbConfig.name}</span>
                  </span>
                </Option>
              );
            })}
          </Select>
        )}
      </Form.Item>
    );
  }
}

// Wrap with Form.create() if using Ant Design v3
// const WrappedComponent = Form.create()(YourComponent);
export default YourComponent;

Key Notes:

  • Fixed valuePropName: I noticed you had valuePropName: 'option'—Ant Design's Select uses value as the default prop name for selected values, so updating this ensures your form field works correctly.
  • Icon Alignment: The flex container for the Option content keeps the icon and text aligned cleanly.
  • Fallback Color: We added a default gray color in case a new type is added later that isn't in our mapping, so your UI won't break unexpectedly.
  • Icon Choice: I used the generic database icon, but you can swap it for more specific icons (like sql for MySQL) if that fits your design better.

This should give you dropdown options where each has an icon colored exactly how you want—elastic in purple, MySQL in green, and MongoDB in gray.

内容的提问来源于stack exchange,提问作者Stack Kiddy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:29:46