应用场景
已知第三方组件提供了少许的属性用于程序控制部分样式,现在要求能控制所有细节。
实现方式
核心思路:使用css变量
这里以antd组件库的Tabs控件为例,控制Tabs被选中的页签字体样式。
定义css class,这里用的sass
.tabs{--active-fontfamily: inherit;--active-fontsize : inherit;--active-fontweight: inherit;--active-fontcolor : inherit;--active-fontstyle : inherit;//事先通过F12工具找到控件使用的class.ant-tabs-tab.ant-tabs-tab-active {.ant-tabs-tab-btn {font-family: var(--active-fontfamily);font-size : var(--active-fontsize);font-weight: var(--active-fontweight);font-style : var(--active-fontstyle);color : var(--active-fontcolor);}}
}
组件逻辑
<Tabs rootClassName="tabs" items={[{key:'1',label:'tab1',children:'tab1pane'},{key:'2',label:'tab2',children:'tab2pane'},
]}/>
const [conf,setConf]=useState({active_fontfamily:'微软雅黑',active_fontsize:14,active_fontweight:500,active_fontstyle:'italic',active_fontcolor:'#66ffcc'
})
useEffect(()=>{//由于ts类型限制,如果直接写在style里会校验不过,因此主动取dom对象赋值const tabs = document.querySelector('.tabs') as HTMLDivElementif(tabs){tabs.style.setProperty('--active-fontfamily', conf.active_fontfamily)tabs.style.setProperty('--active-fontsize', conf.active_fontsize)tabs.style.setProperty('--active-fontweight', conf.active_fontweight)tabs.style.setProperty('--active-fontcolor', conf.active_fontcolor)tabs.style.setProperty('--active-fontstyle', conf.active_fontstyle)}
},[conf])