Material UI's Tooltip - Customization Style

2019-07-10 02:02发布

问题:

How can I change the background color and color for Material UI's Tooltip. I tried as below but it is not working.

import { createMuiTheme } from '@material-ui/core/styles';
export const theme = createMuiTheme({
tooltip: {
        color: '#ffffff',
        rippleBackgroundColor: 'red'
    }
});

import MuiThemeProvider from '@material-ui/core/styles/MuiThemeProvider';
import { theme } from "my-path";

<MuiThemeProvider theme={theme} >
<Tooltip
    title={this.props.title}
    placement={this.props.placement} className="customTooltipStyle">
    <em className="fa fa-info-circle"></em>
</Tooltip>
</MuiThemeProvider>

回答1:

Below are examples of how to override all tooltips via the theme, or to just customize a single tooltip using 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 "./styles.css";

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

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

function App(props) {
  return (
    <div className="App">
      <MuiThemeProvider theme={theme}>
        <Tooltip title="This tooltip is customized via overrides in the theme">
          <div>Hover to see tooltip</div>
        </Tooltip>
      </MuiThemeProvider>
      <Tooltip
        classes={props.classes}
        title="This tooltip is customized via withStyles"
      >
        <div>Hover to see tooltip</div>
      </Tooltip>
    </div>
  );
}
const StyledApp = withStyles(styles)(App);
const rootElement = document.getElementById("root");
ReactDOM.render(<StyledApp />, rootElement);

Here is a working example:

Here is documentation on tooltip CSS classes available to control different aspects of tooltip behavior: https://material-ui.com/api/tooltip/#css

Here is documentation on overriding these classes in the theme: https://material-ui.com/customization/themes/#css