gpt4 book ai didi

javascript - 如何在 React 中动态更改按钮大小和颜色

转载 作者:行者123 更新时间:2023-12-05 02:57:06 27 4
gpt4 key购买 nike

我使用 React 在我的应用程序中创建了一个自定义 Button 组件。截至目前,我可以在其中动态地将颜色更改为我在其中指定的颜色 color属性,但现在我还希望可以选择更改按钮的大小(即“小”、“大”)。我仍然是 CSS 的初学者,所以我不太确定我应该怎么做。

我的 Button.css 文件

.ButtonUI {
border-radius: 4px;
border: none;
padding: 10px 24px;
margin-right: 20px;
margin-left: 20px;
}

.G-green {
color: white;
background-color: #0F9D58;
}

.small {
border-radius: 4px;
border: none;
padding: 6px 12px;
}

.ButtonUI.G-green:hover{
cursor: pointer;
background-color: #0d8c4f;
}

.G-blue {
color: white;
background-color: #4285F4;
}

.ButtonUI.G-blue:hover{
cursor: pointer;
background-color: #336ac4;
}

.G-red {
color: white;
background-color: #DB4437;
}

.ButtonUI.G-red:hover{
cursor: pointer;
background-color: #b0362c;
}

.G-yellow {
color: white;
background-color: #F4B400;
}

.ButtonUI.G-yellow:hover{
cursor: pointer;
background-color: #d19b02;
}

.ata-teal{
color: white;
background-color: #04837B;
}

.ButtonUI.ata-teal:hover{
cursor: pointer;
background-color: #005e58;
}

.ata-orange{
color: white;
background-color: #ffa600;
}

.ButtonUI.ata-orange:hover{
cursor: pointer;
background-color: #db8f00;
}

我的 Button.js 文件

import React from 'react'
import '../../StyleSheets/Button.css'

export default class Button extends React.Component{
constructor(props){
super(props);

this.state = {

}
}

render(){
return(
<div id="button">
<button className={"ButtonUI " + this.props.color + this.props.size} onClick={this.props.click} id={this.props.name}>{this.props.name}</button>
</div>
)
}
}

我试过这样调用组件:<Button color="G-green" size="small" name="Click Me"></Button>但这破坏了我的 CSS,我的按钮显示为空白。

如果有人知道解决这个问题的好方法,我将不胜感激。谢谢!

最佳答案

<button className={`ButtonUI ${this.props.color} ${this.props.size}`} onClick={this.props.click} id={this.props.name}>{this.props.name}</button>

或者

<button className={['ButtonUI', this.props.color, this.props.size].join(' ')} onClick={this.props.click} id={this.props.name}>{this.props.name}</button>

或者如果你想安装 classnames 包,这对条件类非常有用:

import classNames from 'classnames'

<button className={classNames('ButtonUI', this.props.color, this.props.size)} onClick={this.props.click} id={this.props.name}>{this.props.name}</button>

关于javascript - 如何在 React 中动态更改按钮大小和颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59937812/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com