關於react項目中Ant Design組件樣式覆蓋不了的問題

在用react + Ant Design開發項目的時,有時我們有自己的一套UI,這套UI又與原本的Ant Design裏的組件樣式衝突,而爲了實現我們自己的樣式,可做如下處理:

1. 新增class

<Button type="primary">提交</Button>

<!-- 覆蓋方法 -->
<Button type="primary" class="btn-class">提交</Button>
.btn-class {
    ...
    ... !important
}

若無法覆蓋,可在樣式後面增加 !important 

2. 行內樣式

<Button type="primary">提交</Button>

<!-- 覆蓋方法 -->
<Button type="primary" style={{...}}>提交</Button>

3. 正則匹配(推薦)

若項目中已經存在了style屬性和class屬性,還有一些樣式需要覆蓋antd組件的樣式,那麼可以使用css屬性選擇器和正則進行聯合使用。首先找到antd button組件的原生樣式名(以Button組件爲例,它的樣式名爲:ant-btn ant-btn-primary),然後再選擇下面方式之一進行操作:

<Button type="primary">提交</Button>
/* 字符串開始位置匹配 */
button[class^="ant-btn-primary"] {
    ...
}

/* 字符串任意位置匹配 */
button[class*="ant-btn-primary"] {
    ...
}

/* 字符串結束位置匹配 */
button[class$="ant-btn-primary"] {
    ...
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章