Material UI – Global checkbox focus styling (not locally)

后端 未结 2 583
遥遥无期
遥遥无期 2021-01-16 03:21

Trying to alter styling of checkbox when it is focused at a global level using Material-UI (react).

At the moment only default and hover styling is working:

相关标签:
2条回答
  • 2021-01-16 03:39

    The example below shows controlling the color for a bunch of possible states of the Checkbox. Material-UI doesn't manage a focused state for Checkbox, only a focusVisible state, so moving the focus to the Checkbox via the keyboard will trigger that state. I've shown a focused styling in my example below by explicitly managing a focused state using the onFocus and onBlur properties of the Checkbox.

    import React from "react";
    import ReactDOM from "react-dom";
    
    import { createMuiTheme, ThemeProvider } from "@material-ui/core/styles";
    import Checkbox from "@material-ui/core/Checkbox";
    
    const theme = createMuiTheme({
      overrides: {
        MuiCheckbox: {
          colorSecondary: {
            color: "green",
            "&:hover": {
              color: "blue"
            },
            "&$checked": {
              color: "purple",
              "&:hover": {
                color: "lightblue"
              },
              "&.Mui-focusVisible": {
                color: "red"
              }
            },
            "&.Mui-focusVisible": {
              color: "orange"
            },
            "&.focused:not(.Mui-focusVisible):not($checked)": {
              color: "pink"
            }
          }
        }
      }
    });
    function App() {
      const [focused, setFocused] = React.useState(false);
      return (
        <ThemeProvider theme={theme}>
          <div className="App">
            <Checkbox
              className={focused ? "focused" : ""}
              onFocus={() => setFocused(true)}
              onBlur={() => setFocused(false)}
            />
            <input value="somewhere to move focus" />
          </div>
        </ThemeProvider>
      );
    }
    
    const rootElement = document.getElementById("root");
    ReactDOM.render(<App />, rootElement);
    

    0 讨论(0)
  • 2021-01-16 03:41

    its either a problem with specificity or you just need to add the classes you made to your component

    const styles = {
      root: {
        '&$disabled': {
          color: 'white',
        },
      },
      disabled: {},
    };
    

    compiles to:

    .root-x.disable-x {
      color: white;
    }
    

    ⚠️ You need to apply the two generated class names (root & disabled) to the DOM to make it work.

    <Button
      disabled
      classes={{
        root: classes.root, // class name, e.g. `root-x`
        disabled: classes.disabled, // class name, e.g. `disabled-x`
      }}
    >
    

    i get this from the documentaiton

    https://material-ui.com/customization/components/#use-rulename-to-reference-a-local-rule-within-the-same-style-sheet

    0 讨论(0)
提交回复
热议问题