【发布时间】:2025-12-15 16:55:01
【问题描述】:
在使此代码正常工作时遇到了一些问题。只是想使用一个功能而不是 3 个单独的功能来不同地处理每个按钮案例。一些非常古老的 * 答案建议使用开关,但我似乎无法让它工作。下面的代码没有错误,但按下按钮不会向控制台打印任何内容。
myFunction = button => {
var x = button.id;
switch (x) {
case 'All Saves':
console.log('All Saves');
break;
case 'Threads':
console.log('Threads');
break;
case 'Comments':
console.log('Comments');
break;
default:
return false;
}
}
render () {
return (
<div className="container">
<div className="btn-group">
<button type="button" onClick={this.myFunction.bind(this)} id="All Saves">All Saves</button>
<button type="button" onClick={this.myFunction.bind(this)} id="Threads">Threads</button>
<button type="button" onClick={this.myFunction.bind(this)} id="Comments">Comments</button>
</div>
</div>
)
}
【问题讨论】:
-
您将
myFunction定义为变量,而您将点击处理程序定义为this.myFunction。并不总是一样的。 -
你的函数被调用了吗?
-
当您
console.log(x);时会发生什么?还是console.log(button)? -
@VLAZ 不确定我理解你的意思。
-
@SimonThiel 我希望它在点击时被调用。我不会在此之外称呼它。
标签: javascript reactjs button switch-statement