简体   繁体   English

如何设置 MUI 工具提示的样式?

[英]How to style MUI Tooltip?

How can I style MUI Tooltip text?如何设置 MUI Tooltip文本的样式? The default tooltip on hover comes out black with no text-wrap. hover 上的默认工具提示显示为黑色,没有文字换行。 Is it possible to change the background, color etc?是否可以更改背景,颜色等? Is this option even available?这个选项甚至可用吗?

The other popular answer (by André Junges) on this question is for the 0.x versions of Material-UI.关于这个问题的另一个流行答案(由 André Junges)是针对 0.x 版本的 Material-UI。 Below I've copied in my answer from Material UI's Tooltip - Customization Style which addresses this for v3 and v4.下面我从Material UI 的 Tooltip - Customization Style 中复制了我的答案,它针对 v3 和 v4 解决了这个问题。 Further down, I have added a version of the example using v5.再往下,我添加了一个使用 v5 的示例版本。

Below are examples of how to override all tooltips via the theme, or to just customize a single tooltip using withStyles (two different examples).下面是如何通过主题覆盖所有工具提示的示例,或者仅使用 withStyles(两个不同的示例)自定义单个工具提示。 The second approach could also be used to create a custom tooltip component that you could reuse without forcing it to be used globally.第二种方法也可用于创建自定义工具提示组件,您可以重用该组件,而无需强制在全局范围内使用它。

import React from "react";
import ReactDOM from "react-dom";

import {
  createMuiTheme,
  MuiThemeProvider,
  withStyles
} from "@material-ui/core/styles";
import Tooltip from "@material-ui/core/Tooltip";

const defaultTheme = createMuiTheme();
const theme = createMuiTheme({
  overrides: {
    MuiTooltip: {
      tooltip: {
        fontSize: "2em",
        color: "yellow",
        backgroundColor: "red"
      }
    }
  }
});
const BlueOnGreenTooltip = withStyles({
  tooltip: {
    color: "lightblue",
    backgroundColor: "green"
  }
})(Tooltip);

const TextOnlyTooltip = withStyles({
  tooltip: {
    color: "black",
    backgroundColor: "transparent"
  }
})(Tooltip);

function App(props) {
  return (
    <MuiThemeProvider theme={defaultTheme}>
      <div className="App">
        <MuiThemeProvider theme={theme}>
          <Tooltip title="This tooltip is customized via overrides in the theme">
            <div style={{ marginBottom: "20px" }}>
              Hover to see tooltip customized via theme
            </div>
          </Tooltip>
        </MuiThemeProvider>
        <BlueOnGreenTooltip title="This tooltip is customized via withStyles">
          <div style={{ marginBottom: "20px" }}>
            Hover to see blue-on-green tooltip customized via withStyles
          </div>
        </BlueOnGreenTooltip>
        <TextOnlyTooltip title="This tooltip is customized via withStyles">
          <div>Hover to see text-only tooltip customized via withStyles</div>
        </TextOnlyTooltip>
      </div>
    </MuiThemeProvider>
  );
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

编辑工具提示自定义

Here is documentation on tooltip CSS classes available to control different aspects of tooltip behavior: https://material-ui.com/api/tooltip/#css以下是有关可用于控制工具提示行为的不同方面的工具提示 CSS 类的文档: https : //material-ui.com/api/tooltip/#css

Here is documentation on overriding these classes in the theme: https://material-ui.com/customization/components/#global-theme-override以下是关于在主题中覆盖这些类的文档: https : //material-ui.com/customization/components/#global-theme-override


Here is a similar example, but updated to work with v5 of Material-UI:这是一个类似的示例,但已更新以与 Material-UI 的 v5 一起使用:

import React from "react";
import ReactDOM from "react-dom";

import { createTheme, ThemeProvider, styled } from "@material-ui/core/styles";
import Tooltip, { tooltipClasses } from "@material-ui/core/Tooltip";

const defaultTheme = createTheme();
const theme = createTheme({
  components: {
    MuiTooltip: {
      styleOverrides: {
        tooltip: {
          fontSize: "2em",
          color: "yellow",
          backgroundColor: "red"
        }
      }
    }
  }
});
const BlueOnGreenTooltip = styled(({ className, ...props }) => (
  <Tooltip {...props} classes={{ popper: className }} />
))(`
  & .${tooltipClasses.tooltip} {
    color: lightblue;
    background-color: green;
    font-size: 1.5em;
  }
`);

const TextOnlyTooltip = styled(({ className, ...props }) => (
  <Tooltip {...props} classes={{ popper: className }} />
))(`
  & .${tooltipClasses.tooltip} {
    color: black;
    background-color: transparent;
  }
`);

function App(props) {
  return (
    <ThemeProvider theme={defaultTheme}>
      <div className="App">
        <ThemeProvider theme={theme}>
          <Tooltip title="This tooltip is customized via overrides in the theme">
            <div style={{ marginBottom: "20px" }}>
              Hover to see tooltip customized via theme
            </div>
          </Tooltip>
        </ThemeProvider>
        <BlueOnGreenTooltip title="This tooltip is customized via styled">
          <div style={{ marginBottom: "20px" }}>
            Hover to see blue-on-green tooltip customized via styled
          </div>
        </BlueOnGreenTooltip>
        <TextOnlyTooltip title="This tooltip is customized via styled">
          <div>Hover to see text-only tooltip customized via styled</div>
        </TextOnlyTooltip>
      </div>
    </ThemeProvider>
  );
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

编辑工具提示自定义

Documentation on changes to the theme structure between v4 and v5: https://next.material-ui.com/guides/migration-v4/#theme有关 v4 和 v5 之间主题结构更改的文档: https : //next.material-ui.com/guides/migration-v4/#theme

Tooltip customization examples in the Material-UI documentation: https://next.material-ui.com/components/tooltips/#customized-tooltips Material-UI 文档中的工具提示自定义示例: https : //next.material-ui.com/components/tooltips/#customized-tooltips

This answer is out of date.这个答案已经过时了。 This answer was written in 2016 for the 0.x versions of Material-UI.这个答案是在 2016 年为 Material-UI 的 0.x 版本编写的。 Please see this answer for an approach that works with versions 3 and 4.请参阅此答案以了解适用于版本 3 和 4 的方法。

well, you can change the text color and the element background customizing the mui theme.好吧,您可以更改自定义 mui 主题的文本颜色和元素背景。

color - is the text color color - 是文本颜色

rippleBackgroundColor - is the tooltip bbackground rippleBackgroundColor - 是工具提示 bbackground

Example: Using IconButton - but you could you the Tooltip directly..示例:使用IconButton - 但您可以直接使用Tooltip ..

import React from 'react';
import IconButton from 'material-ui/IconButton';
import MuiThemeProvider from 'material-ui/lib/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/lib/styles/getMuiTheme';

const muiTheme = getMuiTheme({
  tooltip: {
    color: '#f1f1f1',
    rippleBackgroundColor: 'blue'
  },
});

const Example = () => (
  <div>
    <MuiThemeProvider muiTheme={muiTheme}>
        <IconButton iconClassName="muidocs-icon-custom-github" tooltip="test" />
    </MuiThemeProvider>
  </div>
);

You can also pass a style object for the Tooltip (in IconButton it's tooltipStyles ) - but these styles will only be applied for the root element.您还可以为Tooltip传递一个style对象(在IconButton它是tooltipStyles ) - 但这些样式只会应用于根元素。

It's not possible yet to change the label style to make it wrap in multiple lines.尚无法更改标签样式以使其包含在多行中。

I ran into this issue as well, and want for anyone seeking to simply change the color of their tooltip to see this solution that worked for me:我也遇到了这个问题,并希望任何寻求简单更改工具提示颜色的人都能看到这个对我有用的解决方案:

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';

import Tooltip from '@material-ui/core/Tooltip';
import Button from '@material-ui/core/Button';
import DeleteIcon from '@material-ui/icons/Delete';

const useStyles = makeStyles(theme => ({
  customTooltip: {
    // I used the rgba color for the standard "secondary" color
    backgroundColor: 'rgba(220, 0, 78, 0.8)',
  },
  customArrow: {
    color: 'rgba(220, 0, 78, 0.8)',
  },
});

export default TooltipExample = () => {
  const classes = useStyles();

  return (
    <>
      <Tooltip
        classes={{
          tooltip: classes.customTooltip,
          arrow: classes.customArrow
        }}
        title="Delete"
        arrow
      >
        <Button color="secondary"><DeleteIcon /></Button>
      </Tooltip>
    </>
  );
};

If you want to change text color , font-size ... of Tooltip there is a simple way.如果你想改变 Tooltip 的 text color , font-size ... 有一个简单的方法。

You can insert a Tag inside Title of Martial Ui Tooltip for example :您可以在武术 Ui 工具提示的标题中插入一个标签,例如:

<Tooltip title={<span>YourText</span>}>
   <Button>Grow</Button>
</Tooltip>

then you can style your tag anyhow you want.然后您可以随意设置标签样式。

check below Example :检查下面的例子:

编辑谦虚-艾伦-6ubp6

Another solution with HtmlTooltip HtmlTooltip 的另一种解决方案

I Use HtmlTooltip and add arrow: {color: '#f5f5f9',}, for the arrow tooltip style.我使用 HtmlTooltip 并为箭头工具提示样式添加arrow: {color: '#f5f5f9',},

And much more to the tooltip style itself.还有更多关于工具提示样式本身的内容。

So I use ValueLabelComponent to control the label and put there a Tooltip from MaterialUI.所以我使用ValueLabelComponent来控制标签并将 MaterialUI 的Tooltip放在那里。

Hopes it give another way to edit MaterialUI Tooltip :)希望它提供另一种编辑 MaterialUI 工具提示的方法:)

const HtmlTooltip = withStyles((theme) => ({
  tooltip: {
    backgroundColor: 'var(--blue)',
    color: 'white',
    maxWidth: 220,
    fontSize: theme.typography.pxToRem(12),
    border: '1px solid #dadde9',
  },
  arrow: {
    color: '#f5f5f9',
  },
}))(Tooltip);

function ValueLabelComponent({ children, open, value }) {
  return (
    <HtmlTooltip arrow open={open} enterTouchDelay={0} placement="top" title={value}>
      {children}
    </HtmlTooltip>
  );
}

...
...

return (
    <div className={classes.root}>
      <Slider
        value={value}
        onChange={handleChange}
        onChangeCommitted={handleChangeCommitted}
        scale={(x) => convertRangeValueToOriginalValue(x, minMaxObj)}
        valueLabelDisplay="auto"
        valueLabelFormat={(x) => '$' + x}
        ValueLabelComponent={ValueLabelComponent}
        aria-labelledby="range-slider"
      />
    </div>
  );

I used makeStyles() and ended with that:我使用了makeStyles()makeStyles()结束:

import React from 'react';
import Grid from '@mui/material/Grid';
import Typography from '@mui/material/Typography';
import Tooltip from '@mui/material/Tooltip';
import InfoOutlinedIcon from '@mui/icons-material/InfoOutlined';
import { makeStyles } from '@material-ui/core/styles';

const styles = makeStyles({
    tooltip: {
        backgroundColor: '#FFFFFF',
        color: '#000000',
        border: '.5px solid #999999',
        fontSize: '.85rem',
        fontWeight: '400'
    }
});

const HeaderTooltip = ({ header, tooltip }) =>
    <Grid container direction="row" alignItems="center" spacing={1}>
        <Grid item>
            <Typography variant='h5'>{header}</Typography>
        </Grid>
        <Grid item>
            <Tooltip title={tooltip} classes={{ tooltip: styles().tooltip }}>
                <InfoOutlinedIcon />
            </Tooltip>
        </Grid>
    </Grid>

export default HeaderTooltip;

MUI v5 Update MUI v5 更新

You can customize the Tooltip by overriding the styles in the tooltip slot.您可以通过覆盖工具提示槽中的样式来自定义Tooltip提示。 There are 3 ways to do that in v5.在 v5 中有 3 种方法可以做到这一点。 For reference, see the customization section of Tooltip .如需参考,请参阅Tooltip自定义部分。 More examples of sx prop and createTheme can be seen here and here .更多关于sx prop 和createTheme例子可以在这里这里看到。

styled()

const ToBeStyledTooltip = ({ className, ...props }: TooltipProps) => (
  <Tooltip {...props} classes={{ tooltip: className }} />
);
const StyledTooltip = styled(ToBeStyledTooltip)(({ theme }) => ({
  backgroundColor: '#f5f5f9',
  color: 'rgba(0, 0, 0, 0.87)',
  border: '1px solid #dadde9',
}));

sx prop sx道具

<Tooltip
  title="Add"
  arrow
  componentsProps={{
    tooltip: {
      sx: {
        bgcolor: 'common.black',
        '& .MuiTooltip-arrow': {
          color: 'common.black',
        },
      },
    },
  }}
>
  <Button>SX</Button>
</Tooltip>

createTheme + ThemeProvider createTheme + ThemeProvider

const theme = createTheme({
  components: {
    MuiTooltip: {
      styleOverrides: {
        tooltip: {
          backgroundColor: 'pink',
          color: 'red',
          border: '1px solid #dadde9',
        },
      },
    },
  },
});

代码沙盒演示

MUI v5 custom component MUI v5 自定义组件

Building on NearHuscarl's answer using sx , the simplest approach for me was to create a custom component to include the styling plus any other properties you want repeated on each tooltip.基于NearHuscarl使用sx的回答,对我来说最简单的方法是创建一个自定义组件,以包含样式以及您想要在每个工具提示上重复的任何其他属性。

For example, the component could display the tooltips on the bottom with an arrow and a larger font size:例如,组件可以在底部显示带有箭头和更大字体大小的工具提示:

const StyledTooltip = ({ title, children, ...props }) => (
  <Tooltip
    {...props}
    title={title}
    placement="bottom"
    arrow
    componentsProps={{
      tooltip: {
        sx: {
          fontSize: '1.125rem',
        },
      },
    }}
  >
    {children}
  </Tooltip>
);

const Buttons = () => (
  <div>
    <StyledTooltip title="This is one">
      <Button>One</Button>
    </StyledTooltip>
    <StyledTooltip title="This is two">
      <Button>Two</Button>
    </StyledTooltip>
  </div>
);

With styledComponent and MUI V5使用 styledComponent 和 MUI V5

import styled from 'styled-components';
....
....

           <StyledTooltip title={tooltip}>
                  <IconTextStyle>
                    {icon}
                    <Label>{label}</Label>
                  </IconTextStyle>
            </StyledTooltip>
const StyledTooltip = styled((props) => (
  <Tooltip classes={{ popper: props.className }} {...props} />
))`
  & .MuiTooltip-tooltip {
    display: flex;
    background-color: #191c28;
    border-radius: 4px;
    box-shadow: 0px 0px 24px #00000034;
  }
`;

I'm created custom Tooltip in the following way我通过以下方式创建了自定义工具提示

import React from 'react'
import Tooltip from '@material-ui/core/Tooltip'
import ErrorOutlineOutlinedIcon from '@material-ui/icons/ErrorOutlineOutlined'
import {
    makeStyles,
    createStyles,
    withStyles,
} from '@material-ui/core/styles'
import Typography from '@material-ui/core/Typography'
import { Divider, Link, Paper } from '@material-ui/core'


const HtmlTooltip = withStyles(theme => ({
    arrow: {
        '&::before': {
            color: 'white'
        }
    },
    tooltip: {
        backgroundColor: '#f5f5f9',
        boxShadow: theme.shadows[8],
        color: 'rgba(0, 0, 0, 0.87)',
        fontSize: 14,
        maxWidth: 800,
        padding: 0,
    },
    tooltipPlacementTop: {
        margin: '4px 0',
    },
}))(Tooltip)

const imageStyles = { root: { color: 'deeppink', height: 20, marginBottom: 0, width: 20 } }

const Image = withStyles(imageStyles)(({ classes }) => (
    <ErrorOutlineOutlinedIcon classes={classes} />
))

const useStyles = makeStyles(theme =>
    createStyles({
        content: {
            border: `1px solid ${theme.palette.grey[300]}`,
            margin: 0,
            minWidth: 600,
            padding: 0,
            zIndex: 1,
        },
        contentInner: {
            padding: theme.spacing(1)
        },
        header: {
            backgroundColor: 'deeppink',
            fontWeight: 'bold',
            padding: theme.spacing(1),
        }
    })
)

export default function CustomTooltip(params) {
    const classes = useStyles()
    const labelDisplay = params.content
    const textDispaly = params.text
    return (
        <>
            {labelDisplay && labelDisplay.length > 20 ? (<HtmlTooltip arrow interactive title={
                <Paper className={classes.content}>
                    <div className={classes.header}>
                        <Typography color='inherit' variant='body1' style={{color: 'white', fontSize: '20px'}}>
                            {params.title}
                        </Typography>
                    </div>
                    <Divider />
                    <div className={classes.contentInner}>
                        {textDispaly}
                    </div>
                </Paper>}
            placement='top'
            >
                <div style={{ alignItems: 'center', display: 'flex', fontSize: '12px', justifyContent: 'space-between' }}>
                    {labelDisplay}<Image/>
                </div>
            </HtmlTooltip>) : (labelDisplay)}
        </>
    )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM