【问题标题】:How can I set the z-index for this select?如何设置此选择的 z-index?
【发布时间】:2020-11-23 03:27:06
【问题描述】:

您好,我想设置以下组件的 z-index:

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' }),
  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}
  />
);

我找到了这个解决方案:

styles={{menu: provided => ({ ...provided, zIndex: 9999, colourStyles })}}

而不是

styles={colourStyles}

但我失去了所有的颜色......

你能帮帮我吗?

代码如下:

https://codesandbox.io/s/condescending-noether-1ee0v?file=/example.js:0-1531

非常感谢!

【问题讨论】:

    标签: css reactjs


    【解决方案1】:

    请注意,如果您使用styles={{colourStyles}} 而不是styles={colourStyles},那么应用程序也会失去颜色。这是因为它没有按应有的方式扩展。但是,styles={{...colourStyles}} 会起作用。在this post 中阅读更多内容。

    所以这段代码应该可以解决你的问题:

    example.js

    export default () => (
      <Select
        [your other props],
        styles={{
          ...colourStyles, 
          ...{control: styles => ({ ...styles, zIndex: 9999})},
        }}
      />
    );
    

    colourStyles{zIndex: 9999} 两个对象被合并的地方(在 ES6 兼容的语法中,请参阅 this post 了解不同的方法)。或者,您可以在 colourStyles 常量内将 zIndex: 9999 附加在 backgroundColor: 'white' 后面。

    经过检查,您可以看到它有效:

    【讨论】:

    • 不幸的是它不起作用,我想添加以下属性:zIndex: 9999 !important 但我不知道该怎么做......
    • 它确实有效,请参阅this Sandbox。如果您检查该元素,您确实会看到 z-index 已相应修改。那么为什么要使用!important
    猜你喜欢
    • 2018-06-20
    • 2016-05-31
    • 2013-05-13
    • 2012-02-28
    • 1970-01-01
    • 1970-01-01
    • 2012-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多