首页 > 解决方案 > 如何减小选择下拉菜单的宽度?

问题描述

我有这个代码:

import React from 'react';
import chroma from 'chroma-js';

import { colourOptions } from './docs/data';
import Select from 'react-select';

const colourStyles = {
  control: styles => ({ ...styles, backgroundColor: 'white', width: '300px' }),
  option: (styles, { data, isDisabled, isFocused, isSelected }) => {
    const color = chroma(data.color);
    return {
      ...styles,
      backgroundColor: isDisabled
        ? null
        : isSelected
        ? data.color
        : isFocused
        ? color.alpha(0.1).css()
        : null,
      color: isDisabled
        ? '#ccc'
        : isSelected
        ? chroma.contrast(color, 'white') > 2
          ? 'white'
          : 'black'
        : data.color,
      cursor: isDisabled ? 'not-allowed' : 'default',

      ':active': {
        ...styles[':active'],
        backgroundColor: !isDisabled && (isSelected ? data.color : color.alpha(0.3).css()),
      },
    };
  },
  multiValue: (styles, { data }) => {
    const color = chroma(data.color);
    return {
      ...styles,
      backgroundColor: color.alpha(0.1).css(),
    };
  },
  multiValueLabel: (styles, { data }) => ({
    ...styles,
    color: data.color,
  }),
  multiValueRemove: (styles, { data }) => ({
    ...styles,
    color: data.color,
    ':hover': {
      backgroundColor: data.color,
      color: 'white',
    },
  }),
};

export default () => (
  <Select
    closeMenuOnSelect={false}
    defaultValue={[colourOptions[0], colourOptions[1]]}
    isMulti
    options={colourOptions}
    styles={colourStyles}
  />
);

我减小了选择的宽度,但我注意到下拉菜单的宽度没有减小...我也想减小它,但我不知道该怎么做...

这是我的代码:

https://codesandbox.io/s/codesandboxer-example-forked-6417p?file=/example.js

这是我想要的图片:

我的目标

我的意思是我只想要黑色区域的宽度。

你能帮我做这件事吗?

非常感谢 !

标签: javascriptreactjs

解决方案


您可以通过以下方式覆盖菜单的宽度来做到这一点:

const colourStyles = {
   control: styles => ({ ...styles, backgroundColor: 'white', width: '300px'}),
   // your other code goes here
   menu: (provided) => ({
       ...provided,
       width: '300px' // specify width you need here 
   })
}

推荐阅读