• react经验14:动态修改第三方组件的样式


    应用场景

    已知第三方组件提供了少许的属性用于程序控制部分样式,现在要求能控制所有细节。

    实现方式

    核心思路:使用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);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    组件逻辑

    <Tabs rootClassName="tabs" items={[
    	{key:'1',label:'tab1',children:'tab1pane'},
    	{key:'2',label:'tab2',children:'tab2pane'},
    ]}/>
    
    • 1
    • 2
    • 3
    • 4
    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 HTMLDivElement
    	if(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])
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
  • 相关阅读:
    二维码智慧门牌管理系统升级解决方案:采集项目的建立与运用
    ref、reactive、toRef、toRefs
    Peter算法小课堂—球盒问题
    七大软件架构设计原则详解
    RTOS任务间通信为什么不用全局变量?
    Redis中的缓存和集群
    Rxjava3 全新详解及常用操作符
    Linux之iptables及firewall超详解
    Python利用pandas获取每行最大值和最小值
    【Android】Nexus 5X 环境配置
  • 原文地址:https://blog.csdn.net/kw269937519/article/details/138157589