需求:
- 上面有一组按钮,每个按钮对应一个颜色,点击那个按钮,选中的tab项就要是这个颜色
vue版的
- 定义一个颜色变量,点击按钮,就赋值给对应的颜色。css中使用v-bind()绑定这个颜色变量,对组件库的tabs组件默认样式进行样式穿透修改
- 现在样式穿透,推荐使用 :deep(选择器)
<template>
<div>
<el-button @click="fillRed">红色</el-button>
<el-button @click="fillGreen">绿色</el-button>
<el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
<el-tab-pane label="User" name="first">User</el-tab-pane>
<el-tab-pane label="Config" name="second">Config</el-tab-pane>
<el-tab-pane label="Role" name="third">Role</el-tab-pane>
<el-tab-pane label="Task" name="fourth">Task</el-tab-pane>
</el-tabs>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import type { TabsPaneContext } from 'element-plus'
const activeName = ref('first')
// 颜色
let selectColor = ref('red')
const handleClick = (tab: TabsPaneContext, e: Event) => {
console.log(tab, e)
}
// 点击红色按钮
const fillRed = () => {
selectColor.value = 'red'
}
// 点击绿色按钮
const fillGreen = () => {
selectColor.value = 'green'
}
</script>
<style scoped>
/* 样式穿透,修改组件库组件的样式 */
:deep(.el-tabs__item.is-top.is-active) {
/* v-bind可以绑定变量 */
color: v-bind(selectColor);
}
</style>
react版的
- 只能通过操作Dom实现,再利用排思想。有一点小瑕疵,就是点击按钮后,它不能立马改变当前选中的这项的颜色
import React, { useState } from 'react'
import { Tabs, Button, Space } from 'antd'
export default function Fff() {
const [color, setColor] = useState('red')
const items = [
{
key: '1',
label: `第一个`,
children: '111',
},
{
key: '2',
label: `第二个`,
children: '222',
},
{
key: '3',
label: `第三个`,
children: `333`,
},
]
const fillRed = () => {
setColor('red')
}
const fillGreen = () => {
setColor('green')
}
return (
<div>
<Space>
<Button onClick={fillRed}>红色</Button>
<Button onClick={fillGreen}>绿色</Button>
</Space>
<Tabs
items={items}
// tabBarStyle={
{ color: 'pink' }}
onTabClick={(_, e) => {
let nodeList = e.target.parentNode.parentNode.children
// 排他思想,使所有颜色都为空,最后再单独给某一项添加颜色
for (let i = 0; i < nodeList.length - 1; i++) {
nodeList[i].children[0].style.color = ''
}
e.target.style.color = color
}}
/>
</div>
)
}
原文链接:https://blog.csdn.net/qq_52845451/article/details/129603201
此处评论已关闭