Javascript 一个函数处理多个按钮
使此代码正常工作时遇到一些问题。只需使用一个功能而不是三个单独的功能来处理每个按钮盒。一些非常古老的stackoverflow答案建议使用开关,但我似乎无法让它工作。下面的代码没有错误,但按下按钮不会将任何内容打印到控制台Javascript 一个函数处理多个按钮,javascript,reactjs,button,switch-statement,Javascript,Reactjs,Button,Switch Statement,使此代码正常工作时遇到一些问题。只需使用一个功能而不是三个单独的功能来处理每个按钮盒。一些非常古老的stackoverflow答案建议使用开关,但我似乎无法让它工作。下面的代码没有错误,但按下按钮不会将任何内容打印到控制台 myFunction = button => { var x = button.id; switch (x) { case 'All Saves': console.log('All Saves
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=button=>{
var x=button.id;
开关(x){
案例“全部保存”:
console.log(“所有保存”);
打破
案例“线程”:
log('Threads');
打破
案例“评论”:
console.log('Comments');
打破
违约:
返回false;
}
}
渲染(){
返回(
全部保存
线程
评论
)
}
您忘记访问事件的目标
属性:
myFunction = button => {
var x = button.target.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;
}
}
使用click事件调用函数:
类应用程序扩展了React.Component{
myFunction=事件=>{
var x=event.target.id;
开关(x){
案例“全部保存”:
console.log(“所有保存”);
打破
案例“线程”:
log('Threads');
打破
案例“评论”:
console.log('Comments');
打破
违约:
返回false;
}
}
render(){
返回(
this.myFunction(e)}id=“所有保存”>所有保存
this.myFunction(e)}id=“Threads”>线程
this.myFunction(e)}id=“Comments”>注释
);
}
}
render(,document.getElementById(“根”))代码>
类MyButtons扩展了React.Component{
myFunction=事件=>{
var x=event.target.id;
开关(x){
案例“全部保存”:
console.log(“所有保存”);
打破
案例“线程”:
log('Threads');
打破
案例“评论”:
console.log('Comments');
打破
违约:
返回false;
}
}
render(){
返回(
this.myFunction(e)}id=“所有保存”>所有保存
this.myFunction(e)}id=“Threads”>线程
this.myFunction(e)}id=“Comments”>注释
);
}
}
render(,document.getElementById(“根”))代码>
您将myFunction
定义为变量,而将单击处理程序定义为this.myFunction
。并不是总会有相同的事情发生。你的函数被调用了吗?当你console.log(x)时会发生什么代码>?或者console.log(按钮)
?@VLAZ不确定我是否理解您的意思。@SimonThiel我希望在单击时调用它。我不认为这是个例外。将按钮
重命名为事件
也很有意义。这是惯例。或者使用此
而不是按钮
@VLAZ-这是行不通的。看看bind
做了什么。注意,bind
正在被使用。@Quentin啊,该死的。忘了吧。你说得对,绑定将阻止它。