React class 组件 - 基于 props 的条件样式

React class components - conditional styling based on props

我正在使用旧版本的 material-ui,无法升级。

我正在尝试根据道具的一些组合来更改 Paper 组件的背景。我认为要求ui重新使用 makeStyles HOC 并不复杂。这可能吗?

我认为问题出在这一行: 类={{根:correctBackgroundColor.root}}

但是 https://v0.material-ui.com/#/components/paper 上的文档毫无帮助地说“其他属性(未记录)应用于根元素。”

import React from "react";

const correctBackgroundColor = {
  root: {
    width: 30,
    height: 30,
    border: "1px solid lightgrey",
    backgroundColor: props => {
      if (props.ledIsOn === true && props.ledColorType === "Green") {
        return "#00FF00";
      }
      if (props.ledIsOn === true && props.ledColorType === "Orange") {
        return "#FFA500";
      } 
    }
  }
};

class ColorChange extends React.Component {
  render() {
    const { classes } = this.props;
    let textToRender = (
      <Paper
        id={this.props.id}
        classes={{ root: correctBackgroundColor.root }}
      />
    );
    return (
      <div>
        <Typography variant="p" className={classes.typography_root}>
          {this.props.textLabel}
        </Typography>
        {textToRender}
      </div>
    );
  }
}

export default withStyles(styles)(ColorChange);

有一个沙箱位于:https://codesandbox.io/s/adoring-bell-oyzsn TIA!

希望我没听错。有两点你应该注意:

首先,correctBackgroundColor无法识别props,因为这超出了范围,因此,我建议将其更改为函数,将道具传递给它,并使函数return一个style object.

其次,我会在将对象应用到 Paper 时使用 style,因此该论文的样式将是使用 props 调用 correctBackgroundColor ,像这样:

<Paper id={this.props.id} style={correctBackgroundColor(this.props)} />

最终代码:

import React from "react";
import withStyles from "@material-ui/core/styles/withStyles";
import Typography from "@material-ui/core/Typography/Typography";
import Paper from "@material-ui/core/Paper/Paper";

const styles = theme => ({
  typography_root: {
    fontSize: 12,
    margin: 10
  }
});
const correctBackgroundColor = props => {
  let bgSwitch = "none";
  if (props.ledIsOn === true && props.ledColorType === "Green")
    bgSwitch = "#00FF00";
  if (props.ledIsOn === true && props.ledColorType === "Orange")
    bgSwitch = "#FFA500";
  if (props.ledIsOn === true && props.ledColorType === "Red")
    bgSwitch = "#FF0000";
  if (props.ledIsOn === true && props.ledColorType === "Grey")
    bgSwitch = "lightGrey";
  return {
    width: 30,
    height: 30,
    border: "1px solid lightgrey",
    backgroundColor: bgSwitch
  };
};

class ColorChange extends React.Component {
  render() {
    const { classes } = this.props;
    let textToRender = (
      <Paper id={this.props.id} style={correctBackgroundColor(this.props)} />
    );
    return (
      <div>
        <Typography variant="p" className={classes.typography_root}>
          {this.props.textLabel}
        </Typography>
        {textToRender}
      </div>
    );
  }
}

export default withStyles(styles)(ColorChange); //with styles injects classes props with styles contained.

Code Sandbox