tmc*_*tmc 7 javascript styling reactjs material-ui
我正在使用旧版本的 material-ui,无法升级。
我正在尝试根据道具的一些组合更改 Paper 组件的背景。我认为要求使用 makeStyles HOC 并不复杂。这可能吗?
我认为问题出在这一行:classes={{ root: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);
Run Code Online (Sandbox Code Playgroud)
有一个沙箱:https : //codesandbox.io/s/adoring-bell-oyzsn TIA!
我希望我说对了你。有两件事你应该注意:
首先,correctBackgroundColor不承认,props因为这超出了范围,因此,我建议将其更改为一个函数,将 props 传递给它,并使该函数返回一个style object.
第二件事情,我会使用style应用对象时Paper,使纸的风格将是一个电话correctBackgroundColor与props,就像这样:
<Paper id={this.props.id} style={correctBackgroundColor(this.props)} />
Run Code Online (Sandbox Code Playgroud)
最终代码:
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.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1329 次 |
| 最近记录: |