programing

MUI에서 활성 탭 색상을 변경하는 방법

easyjava 2023. 3. 5. 10:29
반응형

MUI에서 활성 탭 색상을 변경하는 방법

활성 탭의 색상을 변경하려면 어떻게 해야 합니까?

이거.pink라, 、 진보 、 진을 。

여기에 이미지 설명 입력

스타일 키를 전달할 수 있는 TabIndicatorProps를 지원하는 재료 UI 최신 버전을 사용해 보십시오.

<Tabs TabIndicatorProps={{style: {background:'ANY_COLOR'}}}>......

두 가지 옵션이 있습니다.

테마를 커스터마이즈할 수 있습니다.
httpwww.material-ui.com/#/://www.material-ui.com/#/customization/themeshttp://www.material-ui.com/#//temeshttp

쉬운 은 '우리'를 예요.inkBarStyle★★★★★★★★★★★★★★★★★★.
문서에서도 볼 수 있어요
§:

<Tabs inkBarStyle={{background: 'blue'}}>...

@Risa의 솔루션은 잘 작동하며, 그것이 받아들여지는 답변일 것이다.그녀의 설명에 대한 나의 예는 다음과 같습니다.

<Tabs
  fullWidth
  centered
  classes={{
    indicator: classes.indicator
  }}>
    <Tab />
    <Tab />
</Tabs>

및 스타일:

const styles = theme => ({
  indicator: {
    backgroundColor: 'white',
  },
})

안녕하세요, 색상 변경에 아직 문제가 있는 사람이 있다면 다음 작업을 수행해 주십시오.

<Tabs
  value={value}
  onChange={this.handleChange}
  TabIndicatorProps={{
    style: {
      backgroundColor: "#D97D54"
    }
  }}
>
...
</Tabs>

이거 먹어봐

import { makeStyles} from '@mui/styles';

    const useStyles = makeStyles({
  tabs: {

    "& .MuiTabs-indicator": {
      backgroundColor: "orange",
      height: 3,
    },
    "& .MuiTab-root.Mui-selected": {
      color: 'red'
    }
  }
})

그리고 나서.

const classes = useStyles();
<Tabs
    value={value}
    onChange={handleChange}
    // textColor="secondary"
    // indicatorColor="secondary"
    aria-label="secondary tabs example"
    className={classes.tabs}
    // TabIndicatorProps={{
    //   style: { background: "green", height: 3}
    // }}
  >
  <Tab label={<span className={styles.tabs}>{ABOUT_US}</span>} component={Link} to="/about-us" />
  <Tab label={<span className={styles.tabs}>{ABOUT_HANBANABORINA}</span>} component={Link} to="/about-hanbanaborina" />
  <Tab label={<span className={styles.tabs}>{DOWNLOAD_APPLICATION}</span>} component={Link} to="/download" />
  <Tab label={<span className={styles.tabs}>{HOME}</span>} component={Link} to="/" />
  </Tabs>

여기에 답을 찾지 못해 2019년 업데이트의 마지막을 올렸습니다.많은 답변들이 평가절하된다.

make Style과 material-ui의 styles를 사용하는 것이 큰 번거로움 없이 덮어쓰는 가장 좋은 방법인 것 같습니다.

여기 탭이 있는 예가 있습니다.

makeStyles를 Import해야 합니다.

    import { makeStyles } from '@material-ui/core/styles'
    import Tabs from '@material-ui/core/Tabs'

makeStyles()를 사용한 커스텀 클래스입니다.

     const useStyles = makeStyles((theme) => ({
     customOne: {
        padding: '3rem 15rem',
        flexGrow: 1,
        backgroundColor: theme.palette.background.paper,
        fontFamily: 'Open Sans',
     },
     customTwo: {
        padding: '0rem',
        color: '#484848',
        backgroundColor: 'white',
        fontFamily: 'Open Sans',
        fontSize: '1rem',
    },
   }))

더 많은 오버라이드를 위해 with Styles()를 사용하여 재료 UI(루트 등)별로 사용하는 소품을 사용하는 함수를 만들 수도 있습니다.

    const TabStyle = withStyles((theme) => ({
    root: {
       padding: '1rem 0',
       textTransform: 'none',
       fontWeight: theme.typography.fontWeightRegular,
       fontSize: '1.2rem',
       fontFamily: [
           '-apple-system',
           'BlinkMacSystemFont',
           'Roboto',
       ].join(','),
       '&:hover': {
          backgroundColor: '#004C9B',
          color: 'white',
          opacity: 1,
       },
      '&$selected': {
          backgroundColor: '#004C9B',
          color: 'white',
          fontWeight: theme.typography.fontWeightMedium,
      },
  },
  tab: {
      padding: '0.5rem',
      fontFamily: 'Open Sans',
      fontSize: '2rem',
      backgroundColor: 'grey',
      color: 'black',
      '&:hover': {
          backgroundColor: 'red',
          color: 'white',
          opacity: 1,
      },
  },
  selected: {},
  }))((props) => <Tab {...props} />)

내 컴포넌트에서 const classes = useStyles()를 정의합니다.이것에 의해, 클래스내의 useStyles 소품을 변경할 수 있습니다.

className={classes.custom}과(와) 같은 커스텀 클래스를 사용합니다.하나

    export default function TabsCustom({ activeTabIndex, onChange, values }) {
    const classes = useStyles()
    const [value, setValue] = React.useState(0)

    const handleChange = (event, newValue) => {
       setValue(newValue)
  }


    return (
        <div className={classes.customOne}>
            <Tabs
                className={classes.customTwo}
                variant="fullWidth"
                value={activeTabIndex}
                onChange={onChange}
                aria-label="tabs"
            >
                <TabStyle
                    value="updateDate"
                    icon={(<Icon>insert_invitation</Icon>)}
                    label={i18n.perYear}
                />

            </Tabs>
    </div>
   )
 }

도움이 됐으면 좋겠다.개인적으로 나는 이 설명을 찾았더라면 많은 시간(그리고 고통)을 벌었을 것이다.

예 1:

Js:

<Tabs indicatorColor="primary" classes={{ indicator: classes.indicator }}>

스타일:

indicator:{
      backgroundColor: 'green'
    }

예 2:

<Tabs TabIndicatorProps={{style: {background:'green'}}} >                    

material-ui 버전 1.0.0-beta.36의 경우 다음과 같이 처리되었습니다.

<Tabs indicatorColor={'HEX_COLOR'}>

inkBarStyle은 v1.0에서 indicatorColor에 의해 폐지되거나 대체되어야 합니다.

편집: v1.0 문서 링크: https://material-ui-next.com/api/tabs/

편집: v1.0의 안정적인 릴리스 이후 이전 솔루션은 더 이상 작동하지 않는 것으로 보입니다.

나머지 솔루션은 다음과 같습니다.

  1. ' 는 ' 오버라이드indicator class. 재정의에 대한 문서에 링크합니다.하단에 CSS API 클래스가 있는 docs Tab 컴포넌트에 링크합니다.
  2. 는 원하는 할 수 .primary ★★★★★★★★★★★★★★★★★」secondary그런 원하는 .primary ★★★★★★★★★★★★★★★★★」secondarycolor color color color 。indicatorColorAtribute를 참조해 주세요.문서 링크

클래스 재정의가 더 쉬운 옵션일 수 있습니다. 하다를 요.withStyles커스텀 스타일클래스를 주입하기 위한 컴포넌트입니다.그 이유는 라이브러리의 스타일링이 클래스나 스타일 컴포넌트보다 우선되기 때문입니다.위에 링크된 문서는 좋은 예입니다.

방금 이 질문을 받았습니다. 당신네 사람들에게 도움이 되길 바랍니다.

          <Tabs classes={{ indicator: `your classes like underline` }} >
            <Tab
              classes={{ selected: `your classes like underline` }}
            />
            <Tab
              classes={{ selected: classes.selectedTab }}
            />
          </Tabs>

MUI v5 업데이트

.sx인라인 스타일이 아닌 MUI v5에서 프로포트를 사용할 수 있습니다.사용자 지정 색상을 선언하려면:

<Tabs
  {...}
  TabIndicatorProps={{
    sx: {
      backgroundColor: 'red',
    },
  }}
>

sx속성도 테마를 인식합니다.팔레트의 색상 중 하나를 사용하려면:

<Tabs
  {...}
  TabIndicatorProps={{
    sx: {
      backgroundColor: 'secondary.main',
    },
  }}
>

또는 표시기 색상을 전체적으로 변경하는 경우:

const theme = createTheme({
  components: {
    MuiTabs: {
      styleOverrides: {
        indicator: {
          backgroundColor: 'orange',
          height: 3,
        },
      },
    },
  },
});

라이브 데모

Codesandbox 데모

이제 TabIndicatorProps를 사용하여 현재 버전의 MUI(4.10.02)로 활성 표시기를 스타일링할 수 있습니다.문서는 이쪽에서 구할 수 있습니다.

여기에는 다음 두 가지 방법이 있습니다.

방법 1: 스타일 사용

import React from "react";
import PropTypes from "prop-types";
import { Tabs, Tab, makeStyles } from "@material-ui/core";

const TabsIndicator = () => {
  const [value, setValue] = React.useState(0);

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  return (
    <React.Fragment>
       <Tabs
         value={value}
         onChange={handleChange}
         TabIndicatorProps={{
           style: { background: "cyan", height: "10px", top: "35px" }
         }}
       >
         <Tab label="TEST1" value={0} />
         <Tab label="TEST2" value={1} />
         <Tab label="TEST3" value={2} />
         <Tab label="TEST4" value={3} />
       </Tabs>
    </React.Fragment>
  );
};

export default TabsIndicator;

방법 2: 클래스 사용

import React from "react";
import PropTypes from "prop-types";
import { Tabs, Tab, makeStyles } from "@material-ui/core";

const useStyles = makeStyles(theme => ({
  indicator: {
    backgroundColor: "green",
    height: "10px",
    top: "45px"
  }
}));

const TabsIndicator = () => {
  const classes = useStyles();

  const [value, setValue] = React.useState(0);

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  return (
    <React.Fragment>
        <Tabs
          value={value}
          onChange={handleChange}
          TabIndicatorProps={{ className: classes.indicator }}
        >
          <Tab label="TEST1" value={0} />
          <Tab label="TEST2" value={1} />
          <Tab label="TEST3" value={2} />
          <Tab label="TEST4" value={3} />
        </Tabs>
    </React.Fragment>
  );
};

export default TabsIndicator;

제 샌드박스도 확인하실 수 있습니다.이게 도움이 됐으면 좋겠네요!

Mui v5+를 사용하고 있으며 구성 요소 스타일로 구성하려는 사용자 지정 테마로 재정의:

MuiTab: {
  styleOverrides: {
    root: {
      '&.Mui-selected': {
        color: theme.menuSelected
      }
    }
  }
},
MuiTabs: {
  styleOverrides: {
    indicator: {
      backgroundColor: theme.menuSelected
    }
  }
}

은 ~의 MuiTab을 .<Tab /> 및 에서 MuiTabs로<Tabs />.

MUI v5.2.0

★★★★★★★★★★★★★★의Tabs컴포넌트는 다음에서도 사용할 수 있습니다.TabList사용할 수 있다TabIndicatorPropsTabList ★★★★★★★★★★★★★★★★★」sx 소품

<TabList TabIndicatorProps={{ sx: { backgroundColor: 'green'} }} >
  • sx 할 수하기 위한 입니다.

하시면 됩니다.indicatorColor ★★★★★★★★★★★★★★★★★」textColor의 proper의 Tabs[ UI ] 、 [ UI ] 。

<Tabs
   value={selectedTab}
   indicatorColor="secondary"
   textColor="secondary"
   className="w-full h-64"
>
 ...
</Tabs>

새로운 버전을 사용하는 사용자라면 위의 대부분의 사용자가 작동하지 않을 것입니다.색상을 커스터마이즈 하려면 , 메뉴얼을 참조해 주세요.

https://mui.com/material-ui/customization/palette/

import * as React from 'react';
import {
  createTheme,
  ThemeProvider
} from '@mui/material/styles';
import {
  purple
} from '@mui/material/colors';
import Button from '@mui/material/Button';

const theme = createTheme({
  palette: {
    primary: {
      // Purple and green play nicely together.
      main: purple[500],
    },
    secondary: {
      // This is green.A700 as hex.
      main: '#11cb5f',
    },
  },
});

export default function Palette() {
  return ( <
    ThemeProvider theme = {
      theme
    } >
    <
    Button > Primary < /Button> <
    Button color = "secondary" > Secondary < /Button> <
    /ThemeProvider>
  );
}

이것은 꽤 오래된 질문이지만, 여전히 주목을 받고 있으며, 여러 개의 맞춤형 테마를 사용하고 있는 사람들에게 이것은 번거로운 일입니다.테마에 따라 다양한 색상으로 커스터마이즈할 수 있는 더 좋은 솔루션이 있습니다.

먼저 Tabs 구성 요소에 이 방법으로 추가하여 후크할 수 있는 클래스를 만듭니다.

<Tabs
   onChange={this.handleChange}
   value={this.state.slideIndex}
   className="dashboard-tabs"> //this is what you need
       <Tab label="Main" value={0}/>
       <Tab label="Analytics" value={1}/>
       <Tab label="Live Widgets" value={2}/>
</Tabs>

탭과 탭이 다를 수 있으므로 className 행에만 주의하십시오.원하는 이름을 붙일 수 있습니다. 1.다른 밑줄이 있는 다른 탭을 원하는 경우 대시보드에 탭이 있는 경우 대시보드 탭, 퀵패널 탭이 있는 경우 퀵패널 탭 등 의미 있는 이름을 붙입니다.2. 기본적으로 탭이 같다면 material-tab처럼 글로벌하게 이름을 붙이면 어디에서나 클래스를 사용할 수 있습니다.이 작업을 다시 만들지 않아도 됩니다.

이제 이 클래스를 후크 클래스로 사용하고 특수성을 사용하여 다음과 같이 밑줄에 도달합니다.

.dashboard-tabs > div{
    background-color: #333 !important;
}
.dashboard-tabs > div:nth-child(2) > div{
    background-color: #ddd !important;
}

!중요한 것에 대해서는 걱정하지 마세요.!important를 사용하는 것이 나쁘다는 것은 모두 큰 탭일 뿐입니다.좀 좋아질 거예요.

여기 SCSS 샘플이 있습니다.

.dashboard-tabs{
    > div{
        background-color: $bg-color-meddark !important;
        &:nth-child(2){
            > div{
                background-color: $brand-info !important;
            }
        }
    }
}

이 솔루션은 여러 테마를 사용하는 경우 매우 유용합니다. 왜냐하면 (주제가 올바르다고 가정할 때) 위의 코드에 UI를 한 색에서 다음 색상으로 변경하는 동적 테마 클래스를 추가해야 하기 때문입니다.두 가지 테마가 있다고 칩시다.1은 가볍고 테마 클래스를 사용합니다.light-theme그리고 2는 어두운 주제이고dark-theme학급

이 작업은 다음과 같이 수행할 수 있습니다.

.light-theme .dashboard-tabs > div{
    background-color: #fff !important;
}
.light-theme .dashboard-tabs > div:nth-child(2) > div{
    background-color: #333 !important;
}
.dark-theme .dashboard-tabs > div{
    background-color: #333 !important;
}
.dark-theme .dashboard-tabs > div:nth-child(2) > div{
    background-color: #ddd !important;
}

말이 되나요?

InkBarStyle 솔루션에 반대하는 이유는 무엇입니까?배경색을 다른 색으로 대체해도 테마 간에 변경할 수 없기 때문입니다.

행운을 빌어요, 모두들!

다음은 프로젝트에서 사용할 테마 템플릿입니다.

'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

let _colors = require('material-ui/styles/colors');
let _colorManipulator = require('material-ui/utils/colorManipulator');
let _spacing = require('material-ui/styles/spacing');
let _spacing2 = _interopRequireDefault(_spacing);

function _interopRequireDefault(obj) {
  return obj && obj.__esModule ? obj : {default: obj};
}

exports.default = {
  spacing: _spacing2.default,
  fontFamily: 'Roboto, sans-serif',
  borderRadius: 2,
  palette: {
    primary1Color: _colors.grey50,
    primary2Color: _colors.cyan700,
    primary3Color: _colors.grey600,
    accent1Color: _colors.lightBlue500,
    accent2Color: _colors.pinkA400,
    accent3Color: _colors.pinkA100,
    textColor: _colors.fullWhite,
    secondaryTextColor: (0, _colorManipulator.fade)(_colors.fullWhite, 0.7),
    alternateTextColor: '#303030',
    canvasColor: '#303030',
    borderColor: (0, _colorManipulator.fade)(_colors.fullWhite, 0.3),
    disabledColor: (0, _colorManipulator.fade)(_colors.fullWhite, 0.3),
    pickerHeaderColor: (0, _colorManipulator.fade)(_colors.fullWhite, 0.12),
    clockCircleColor: (0, _colorManipulator.fade)(_colors.fullWhite, 0.12)
  }
};

2021 및 버전 4.11.1에서는 다음을 수행할 수 있습니다.

import Tabs from '@material-ui/core/Tabs';
import { withStyles } from '@material-ui/core/styles';

const StyledTabs = withStyles({
  indicator: {
    backgroundColor: 'orange'
  }
})(Tabs);

탭 대신 스타일드탭을 사용합니다.

문서에 대한 링크:

https://material-ui.com/api/tabs/ #css

https://material-ui.com/customization/components/ #syslog 및

JQuery의 JavaScript로 애니메이션 된 분홍색 div를 만들 수 있습니다.탭과 같은 색상의 녹색 디바이드 안에 고정됩니다.

언급URL : https://stackoverflow.com/questions/37324691/how-to-change-active-tab-color-in-mui

반응형