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>
)
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…