[英]Click only once
我有一些反應代碼。 那里有帶onClick功能的按鈕。 當我單擊按鈕時,分數將增加一分。
我要這樣做,以便當我單擊按鈕時它給得分加一分,單擊一次它就不能再加一分
怎么做?
class Toggle extends React.Component { constructor(props) { super(props); this.state = { result: 2, score: 0 }; this.getRes = this.getRes.bind(this); } getRes() { if (this.state.result == 2) { this.setState({score: this.state.score+1}) } } render() { return ( <div> <div style={{paddingTop: 10}}> <p> <button>1</button> <button onClick={this.getRes}>{this.state.result}</button> </p> <p>{this.state.score}</p> </div> </div> ); } } ReactDOM.render( <Toggle />, document.getElementById('root') );
嘗試以這種方式重新組織代碼,方法是引入禁用屬性以在首次單擊后禁用按鈕
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {
disabled: false,
result:2,
score: 0
};
this.getRes = this.getRes.bind(this);
}
getRes() {
this.setState({disabled: true, result:this.state.result+1})
}
render() {
return (
<div>
<div style={{paddingTop: 10}}>
<p>
<button>1</button>
<button onClick={this.getRes} disabled={this.state.disabled}>{this.state.result}</button>
</p>
<p>{this.state.score}</p>
</div>
</div>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById('root')
);
我不確定我是否理解正確,但是當得分為1或更高時,您可以禁用按鈕:
<button onClick={this.getRes} disabled={this.state.score >= 1}>
{this.state.result}
</button>
或按您的方法檢查它:
getRes() {
if (this.state.score >= 1) {
return;
}
if (this.state.result == 2) {
this.setState({
score: this.state.score + 1
})
}
}
或在您的州添加其他字段:
constructor(props) {
super(props);
this.state = {
disabled: false,
result: 2,
score: 0,
clicked: false,
};
this.getRes = this.getRes.bind(this);
}
getRes() {
this.setState({
result: this.state.result + 1,
clicked: true,
})
}
render() {
return (
<div>
<div style={{ paddingTop: 10 }}>
<p>
<button>1</button>
<button onClick={this.getRes} disabled={this.state.clicked}>
{this.state.result}
</button>
</p>
<p>{this.state.score}</p>
</div>
</div>
);
}
}
像這樣添加狀態is_click:true
this.state = {
result: 2,
score: 0,
is_click:true,
};
getRes() {
this.setState({
result: this.state.result + 1,
clicked: true,
is_click:false
})
}
一旦用戶onclick將setstate設置為false並添加到按鈕disable = {this.state.is_click}
<button onClick={this.getRes} disabled={this.state.is_click}>{this.state.result}</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.