反应道具中的样式

时间:2019-03-14 13:22:51

标签: reactjs styling

我为材质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);

1 个答案:

答案 0 :(得分:0)

我认为必须提到{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>
  );
};
相关问题