gpt4 book ai didi

javascript - 单击时更改按钮的颜色? ( react +引导)

转载 作者:太空宇宙 更新时间:2023-11-04 06:28:36 25 4
gpt4 key购买 nike

我正在尝试创建类似于 Reddit 赞成票和反对票系统的“赞成票/反对票”。

我希望能够将对象的状态/颜色更改为绿色(如果单击赞成)或红色(如果单击反对)。

但是,我不希望用户能够点击两次竖起大拇指并从绿色变为默认白色...有什么想法吗?

class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {counter: 0}
}

increment = (e) => {
e.preventDefault();
this.setState({
counter: this.state.counter + 1
});
}

decrement = (e) => {
e.preventDefault();
this.setState({
counter: this.state.counter - 1
});
}

render() {
return (
<div className="voting">
{this.state.counter}
<button className="upvoteBtn" type="submit" onClick={this.increment}>
<i className="fa fa-thumbs-up ml-2 mr-2"/>
</button>
<button className="downvoteBtn" type="submit" onClick={this.decrement}>
<i className="fa fa-thumbs-down ml-2 mr-2"/>
</button>
</div>
)
}
}

最佳答案

这可能会给你一个想法。单击向上或向下按钮后,它将禁用这两个按钮。您还可以在 handleUp 和 handleDown 中实现计数器功能:

class Sample extends React.Component {
constructor(props) {
super(props);
this.state = {
colorUp: 'secondary',
colorDown: 'secondary',
clicked: false
};

this.handleUp = this.handleUp.bind(this);
this.handleDown = this.handleDown.bind(this);
}

handleUp(event) {
if (this.state.clicked === false) {
this.setState({
colorUp: 'success',
clicked: true
});
}
}

handleDown(event) {
if (this.state.clicked === false) {
this.setState({
colorDown: 'danger',
clicked: true
});
}
}

render() {
return (
<div>
<ReactBootstrap.Button className='ml-3' variant={this.state.colorUp} onClick={this.handleUp} disabled={this.state.clicked}>Up</ReactBootstrap.Button>
<ReactBootstrap.Button className='ml-3' variant={this.state.colorDown} onClick={this.handleDown} disabled={this.state.clicked}>Down</ReactBootstrap.Button>
</div>
);
}
}

ReactDOM.render(
<Sample />,
document.getElementById('root')
);
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/react-bootstrap@next/dist/react-bootstrap.min.js" crossorigin></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css" crossorigin="anonymous">

<div id="root" />

关于javascript - 单击时更改按钮的颜色? ( react +引导),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54872107/

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