Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

reactjs - How to Change Color of Button Material UI Tag on React js after Clicked?

i have created w multi step register form and to do the validation it gives error and want to do the validation with this format export const CreateAccount extends Component like this i wan


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can store the current color of the button in the state and just switch its value when the button is clicked. Something like this:

const DynamicButton = () => {
  const [color, setColor] = useState("primary")

  const switchColor = () => {
    if (color === "primary") setColor("secondary")
    else setColor("primary")
  }

  return (
    <Button
      color={color}
      onClick={switchColor}
      variant="contained"
    >
      Click me to change my color!
    </Button>
  )
}

This is using React hooks. But if you are using React class components the equivalent code would be like this:

class DynamicButton extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      color: "primary"
    }
  }

  switchColor = () => {
    if (this.state.color === "primary") this.setState({ color: "secondary" })
    else this.setState({ color: "primary" })
  }

  render() {
    return (
      <Button
        color={this.state.color}
        onClick={this.switchColor}
        variant="contained"
      >
        Click me to change my color!
      </Button>
    )
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...