reactjs - 道具中的反应样式
问题描述
我为材质 ui 按钮做了一些样式,现在我想将style={{backgroundColor}}
部分移动到函数的顶部,就在返回之前。
有人知道该怎么做吗?
const styles = {
root: {
color: "#FFFFFF",
backgroundColor: "#05164D",
transition: "linear 0.5s",
"&:hover": {
opacity: 0.9,
boxShadow: "0 3px 5px 2px rgba(153, 153, 153, .8)"
}
}
};
const StyledButton = props => {
const { classes } = props;
let customColor = props.customColor || "#05164D";
let backgroundColor = customColor;
return (
<div>
<IconButton
className={classes.root}
{...props}
aria-label="StyledButton"
style={{ backgroundColor }}
/>
</div>
);
};
export default withStyles(styles)(StyledButton);
解决方案
我认为重要的是要提到它{backgroundColor}
是{backgroundColor: backgroundColor}
. 所以在 ES6 中你可以简单地使用变量名,如果属性的值应该和变量名一样的话。这个变量在花括号内初始化,花括号包裹了属性值。这就是为什么{{ backgroundColor }}
。如果要初始化渲染上方的变量,可以这样做。
const StyledButton = props => {
const { classes } = props;
let customColor = props.customColor || "#05164D";
let style = { backgroundColor: customColor };
return (
<div>
<IconButton
className={classes.root}
{...props}
aria-label="StyledButton"
style={style}
/>
</div>
);
};
推荐阅读
- r - 错误:在“模拟”中:缺少参数“参数”,没有默认值
- android - 切换到选项卡式布局中的另一个选项卡时未调用片段 onStart() 和 onStop()
- flutter - 元素类型'List
'不能分配给列表类型'Widget' - ios - 确定 URL 是否为目录的最可靠方法?
- c - 在C中模拟javascript的setTimeout和setInterval
- flutter-layout - 如何使 Listview 内的 HorizontalListView 在颤动中具有动态高度?
- mongodb - 无法从节点连接到 docker 中的 mongo 副本集
- docker - 使用 nginx 缺少片段/fastcgi-php.conf 设置 docker-compose
- php - 如何使用 php 处理空对象属性
- flutter - SizedBox 中的 Flutter 图像被父 Container 覆盖