Ant Design 中覆盖组件样式

业务场景:

由于业务的个性化需求,我们经常会遇到需要覆盖组件样式的情况,这里举个简单的例子。

antd Select 在多选状态下,默认会展示所有选中项,这里我们给它加一个限制高度,超过此高度就出滚动条

代码:

// TestPage.less
.customSelect {
  :global {
    .ant-select-selection {
      max-height: 51px;
      overflow: auto;
    }
  }
}
// TestPage.js
import { Select } from 'antd';
import styles from './TestPage.less'
const Option = Select.Option;

const children = [];
for (let i = 10; i < 36; i++) {
  children.push(<Option key={i.toString(36) + i}>{i.toString(36) + i}</Option>);
}

ReactDOM.render(
  <Select
    mode="multiple"
    style={{ width: 300 }}
    placeholder="Please select"
    className={styles.customSelect}
  >
    {children}
  </Select>
, mountNode);

有两点需要注意:

  • 引入的 antd 组件类名没有被 CSS Modules 转化,所以被覆盖的类名 .ant-select-selection 必须放到 :global 中。

  • 因为上一条的关系,覆盖是全局性的。为了防止对其他 Select 组件造成影响,所以需要包裹额外的 className 限制样式的生效范围。

猜你喜欢

转载自www.cnblogs.com/nhz-M/p/10624972.html