单击期间更改样式

时间:2018-12-08 17:49:55

标签: css reactjs button frontend material-ui



我有ReactJS项目,我想在单击期间更改按钮的颜色。我知道这是一个Ripple API,但使用它非常难以理解。有人可以告诉我我该怎么做吗?

我尝试创建两个元素-父级和子级-并在单击时将子级的背景更改为透明。不幸的是,如果按钮处于活动状态并且不起作用,我还拥有“类”对象,负责更改类。 我的代码如下:

import React, { Component } from 'react';
import { withStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import PropTypes from 'prop-types';
import styles from './MydButton.style';

class MyButton extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isClicked: false
    };
  }

  handleClick = () => {
    this.setState({ isClicked: !this.state.isClicked });
  }

  render() {
    const {
      classes,
      children,
      color,
      disabled,
      className,
      onClick,
      type,
      border,
      ...props
    } = this.props;

    const myClass = this.state.isClicked ? 'auxClass' : 'buttonDefaultRoot';


    return (
      <div className={classes.parentRoot} >
        <Button
          classes={{
            root: disabled
            ? classes.buttonDisabledRoot
            : classes.buttonRoot,
            label: disabled 
            ? classes.buttonLabelDisabled 
            : classes.buttonLabel,
          }}
          {...props}
          onClick={this.handleClick}
          className={myClass}
          disabled={disabled}
          type={type === undefined ? 'button' : type}
        >
          {children}
        </Button>
      </div>
    )
  }
};

MyButton.propTypes = {
  children: PropTypes.string.isRequired,
  disabled: PropTypes.bool,
  classes: PropTypes.object.isRequired,
};

MyButton.defaultProps = {
  disabled: false,
};

export default withStyles(styles)(MyButton);

和样式:

    const buttonRoot = {
      border: 0,
      height: 48,
      width: '100%',
    }


export default theme => ({
  buttonDefaultRoot: {
    ...buttonRoot,
    transition: 'all 1s ease-in-out',
    backgroundImage: 'linear-gradient(to right, #F59C81, #E65DA2, #E65DA2, #B13A97, #881E8E)',
    boxShadow: '0px 1px 3px rgba(0, 0, 0, 0.16)',
    backgroundSize: '300% 100%',
    marginTop: 0,
    '&:hover': {
      backgroundPosition: '100% 0%',
      transition: 'all 1s ease-in-out',
    }
  },

  parentRoot: {
       ...buttonRoot,
       backgroundColor: 'red',   
       backgroundSize: '300% 100%',
        marginTop: 36,
      }, 

      auxClass: {
        backgroundImage: 'none',
      },

1 个答案:

答案 0 :(得分:0)

ReactJS的材料UI核心

文档非常好。我已经更新了答案,以适应该问题的特定需求。对于那些偶然发现此问题的人,我还提供了两种通用解决方案。

量身定制的解决方案:

将按钮的背景色从classes.buttonDefaultRoot(问题所有者定义的颜色)更改为该问题所有者定义的渐变。

第一步,将变量存储在状态中。您可以随心所欲地调用它,但我正在调用bgButton。像这样将其设置为this.props.classes.buttonDefaultRoot

state = {
  bgButton: this.props.classes.buttonDefaultRoot,
}

接下来,您要定义将处理单击的函数。再次,将其命名为您想要的。我将其称为handleClick

handleClick = () => {
    const { classes } = this.props; //this grabs your css style theme
    this.setState({ bgButton: classes.parentRoot.auxClass }); //accessing styles
  };

这里发生了几件事。首先,我正在破坏道具。因此,我正在创建一个名为const的新classes变量,该变量的值与this.props.classes相同。 classes包含一组对象,这些对象定义了按钮,边距等的css样式。您可以访问这些样式,就像您尝试获取道具中道具的价值一样。对象

在这种情况下,您可以执行classes.buttonDefaultRoot来访问按钮样式。那会照顾您的手柄点击功能。

最后一步:渲染按钮。在渲染方法中,您要像这样从状态中抓取bgButton

render() {
  const { bgButton } = this.state; 

然后,您想将按钮的className分配给bgButton并添加如下的onClick功能(此方法遵循Material UI Core文档):

<Button variant="contained" color="primary" className={classNames(bgButton)} onClick={this.handleClick}>Button Name</Button>

将所有内容放在一起,您会得到:

import React, { Component } from "react";
import Button from "@material-ui/core/Button";
import PropTypes from "prop-types";
import classNames from "classnames";
import { withStyles } from "@material-ui/core/styles";

export default theme => ({ ... }) //not going to copy all of this

class MyButton extends Component {
  state = {
    bgButton: null
  };
  handleClick = () => {
    const { classes } = this.props;
    this.setState({ bgButton: classes.parentRoot.auxClass });
  };
  render() {
    const { bgButton } = this.state;
    return (
      <div className={classes.container}>
        <Button
          variant="contained"
          color="primary"
          className={classNames(bgButton)}
          onClick={this.handleClick}
        >
          Custom CSS
        </Button>
      </div>
    );
  }
}

MyButton.propTypes = {
  classes: PropTypes.object.isRequired
};

export default withStyles(styles)(MyButton);

常规解决方案

此解决方案适用于想要使用预定义颜色(即默认,主要,辅助,继承)的用户。此实现不需要PropTypes或className导入。这会将颜色从预定义的蓝色更改为预定义的粉红色。而已。

state = {
  bgButton: "primary", 
} 
handleClick = () => {
  this.setState({ bgButton: "secondary" }); 
} 

render() {
  const { bgButton } = this.state; 
  return(
   ...
   <Button
     onClick = {this.handleClick} 
     variant = "contained" //checked Material UI documentation
     color={bgButton}
    > ..etc.

常规解决方案2

要在按钮上适应您的自定义样式,您将必须导入PropTypes和classNames并采用与上述定制解决方案类似的方法。唯一的区别是我的语法和类名。我在这里密切关注文档,因此您可以轻松地进行后续操作,并在必要时进行调整。

    import React, { Component } from "react";
    import Button from "@material-ui/core/Button";
    import PropTypes from "prop-types";
    import classNames from "classnames";
    import { withStyles } from "@material-ui/core/styles";
    import purple from "@material-ui/core/colors/purple";

    const styles = theme => ({
      container: {
        display: "flex",
        flexWrap: "wrap"
      },
      margin: {
        margin: theme.spacing.unit
      },
      cssRoot: {
        color: theme.palette.getContrastText(purple[500]),
        backgroundColor: purple[500],
        "&:hover": {
          backgroundColor: purple[700]
        }
      },
      bootstrapRoot: {
        boxShadow: "none",
        textTransform: "none",
        fontSize: 16,
        padding: "6px 12px",
        border: "1px solid",
        backgroundColor: "#007bff",
        borderColor: "#007bff",
        fontFamily: [
          "-apple-system",
          "BlinkMacSystemFont",
          '"Segoe UI"',
          "Roboto",
          '"Helvetica Neue"',
          "Arial",
          "sans-serif",
          '"Apple Color Emoji"',
          '"Segoe UI Emoji"',
          '"Segoe UI Symbol"'
        ].join(","),
        "&:hover": {
          backgroundColor: "#0069d9",
          borderColor: "#0062cc"
        },
        "&:active": {
          boxShadow: "none",
          backgroundColor: "#0062cc",
          borderColor: "#005cbf"
        },
        "&:focus": {
          boxShadow: "0 0 0 0.2rem rgba(0,123,255,.5)"
        }
      }
    });

    class MyButton extends Component {
      state = {
        bgButton: null
      };
      handleClick = () => {
        const { classes } = this.props;
        this.setState({ bgButton: classes.cssRoot });
      };
      render() {
        const { classes } = this.props; //this gives you access to all styles defined above, so in your className prop for your HTML tags you can put classes.container, classes.margin, classes.cssRoot, or classes.bootstrapRoot in this example. 
        const { bgButton } = this.state;
        return (
          <div className={classes.container}>
            <Button
              variant="contained"
              color="primary"
              className={classNames(bgButton)}
              onClick={this.handleClick}
            >
              Custom CSS
            </Button>
          </div>
        );
      }
    }
MyButton.propTypes = {
  classes: PropTypes.object.isRequired
};

export default withStyles(styles)(MyButton);

提示。您不再需要构造函数或绑定方法。

希望这会有所帮助。