Send Variable to withStyles in Material UI?

2019-07-31 01:51发布

问题:

I have the following:

class StyledInput extends React.Component{


  styles = (color, theme) => ({
    underline: {
      borderBottom: `2px solid ${color}`,
      '&:after': {
        borderBottom: `2px solid ${color}`,
      }
    }
  })

  div = props => (
    <TextField
    placeholder="temp input"
    InputProps={{
      classes:{
        root: props.classes.underline
      },
      style:{
        height: '1.5rem',
        fontSize:'1rem',
        marginTop: '-1rem',
      }
    }}
    >
      <div>
        {props.children}
      </div>
    </TextField>
  )

  Styled = withStyles(this.styles('white'))(this.div)

  render(){
    return(
      <div>
        <this.Styled>{this.props.children}</this.Styled>
      </div>
    );
  }
}

export default StyledInput;

So what this does is it successfully takes a material UI text field and changes the bottom bar to be white, as opposed to blue, when the user clicks the field. Great!

...however...

What I would really like to do is something like

<this.Styled color={someDefinedColor}>{this.props.children}</this.Styled>

where Styled would then look like this:

Styled = (color) => withStyles(this.styles(color))(this.div)

so that I can dynamically pass colors to the Styled attribute. Clearly this is pseudo-code - I've been playing with it, but can't get it to fall through. As a general statement, material-ui is a bit of a bummer to dynamically change colors, so I was wondering if anyone knew how to get this to work.

Thanks!

SOLUTION...although not great.

I'm not sure how to use pseudo-elements with makeStyles and functional components, but this is a solution that seems to work for my purposes. Adding it here for posterity in case anyone else may find it useful:

class StyledInputInner extends React.Component{

  styles = (color, theme) => ({
    underline: {
      '&:before': {
        borderBottom: `2px solid ${color}`,
      },
      '&:after': {
        borderBottom: `2px solid ${color}`,
      },
      '&:hover:not($disabled):before': {
        backgroundColor: `2px solid ${color}`
      },
      '&$focused:after': {
        borderBottom: `2px solid ${color}`
      },
    }
  })  

  textField = props => (
    <TextField
    placeholder="temp input"
    InputProps={{
      classes:{
        root: props.classes.underline
      },
      style:{
        height: '1.5rem',
        fontSize:'1rem',
        marginTop: '-1rem',
      }
    }}
    onClick={()=>this.props.onClick()}
    onChange={(evt)=>{this.props.onChange(evt)}}
    >
      <div>
        {props.children}
      </div>
    </TextField>
  )

  StyledTextField = withStyles(this.styles(this.props.color))(this.textField)

  render(){
    return(
      <div>
        <this.StyledTextField>{this.props.children}</this.StyledTextField>
      </div>
    );
  }
}

class StyledInput extends Component {
  render(){
    return(
      <MainContext.Consumer>
      {stateData => {
        return(
          <StyledInputInner 
          color={stateData.state.InputColor}
          onChange={(evt)=>this.props.onChange(evt)}
          onClick={this.props.onClick}
          > 
            {this.props.children} 
          </StyledInputInner>
        )      
      }}
      </MainContext.Consumer>
    )
  }
}

export default StyledInput;

回答1:

Here is an example of how to do this using the new hook syntax:

index.js

import React from "react";
import ReactDOM from "react-dom";
import StyledComponent from "./StyledComponent";
const CustomComponent = ({ children, className }) => {
  return (
    <p className={className}>
      Just showing passing in the component to use rather than automatically
      using a div.
      <br />
      {children}
    </p>
  );
};
function App() {
  return (
    <div className="App">
      <StyledComponent color="green">
        Here's my content with green underline
      </StyledComponent>
      <StyledComponent
        component={CustomComponent}
        color="blue"
        hoverColor="orange"
      >
        Here's my content with blue underline that changes to orange on hover.
      </StyledComponent>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

StyledComponent.js

import React from "react";
import { makeStyles } from "@material-ui/styles";
const useStyles = makeStyles({
  root: {
    borderBottom: ({ color }) => `2px solid ${color}`,
    "&:hover": {
      borderBottom: ({ color, hoverColor }) => {
        const borderColor = hoverColor ? hoverColor : color;
        return `2px solid ${borderColor}`;
      }
    }
  }
});

const StyledComponent = ({
  component: ComponentProp = "div",
  children,
  color,
  hoverColor
}) => {
  const classes = useStyles({ color, hoverColor });
  return <ComponentProp className={classes.root}>{children}</ComponentProp>;
};

export default StyledComponent;

If you wanted, you could put this useStyles method in its own file and re-use it as a custom hook to make the classes it generates (still with variable support) available to multiple components (rather than just StyledComponent).