gpt4 book ai didi

javascript - React 类组件 - 基于 props 的条件样式

转载 作者:行者123 更新时间:2023-12-01 15:22:11 25 4
gpt4 key购买 nike

我正在使用旧版本的 material-ui,无法升级。
我正在尝试根据 Prop 的一些组合来更改 Paper 组件的背景。我认为要求使用 makeStyles HOC 并不复杂。这可能吗?
我认为问题在于这一行:
类={{ 根:正确背景颜色.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蒂亚!

最佳答案

我希望我说对了。您应该注意两点:
一、correctBackgroundColor无法识别 props因为这超出了范围,因此,我建议将其更改为函数,将 Prop 传递给它,并使函数返回 style object .
第二件事,我会使用 style将对象应用于 Paper 时, 所以那篇论文的风格是调用 correctBackgroundColorprops , 像这样:

<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

关于javascript - React 类组件 - 基于 props 的条件样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62912762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com