我正在尝试创建一个类似Reddit upvote and downvote系统的“ upvote / downvote”大拇指。
我希望能够将对象的状态/颜色更改为绿色(如果单击了大拇指)或红色(如果单击了大拇指)。
但是,我不希望用户单击两次竖起大拇指,然后从绿色变为默认的白色...有什么想法吗?
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>
)
}
}
答案 0 :(得分:1)
这可能会给您一个想法。单击向上或向下按钮后,将同时禁用这两个按钮。您还可以在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" />