如何将两个函数绑定到 React 中的按钮单击
How to bind two functions to a button click in React
我正在尝试将 2 个函数绑定到 reactjs 按钮中的同一个 onClick
事件。
我在这里看到了几个例子,但它们对我不起作用;要么语法不同,要么我的代码逻辑不支持单击一个按钮内的两个功能。这是我正在做的一个例子:
class Example extends Component {
state = {
test:1
}
//function 1
add() {
this.setState({
test: this.state.test+1
});
}
//function 2
somefunc() {
// does smthng
}
render() {
return (
<div>
<Button color = 'success'
onClick={this.add.bind(this)}>+1
</Button>
</div>
)
}
}
上面的代码有效。但是我需要能够向 onClick
添加第二个 (somefunc()
) 函数。像这样:
onClick={() => {this.add.bind(this); this.somefunc.bind(this)}}
绑定可以吗?如果没有,请您解释一下如何在没有绑定的情况下调用函数。
在构造函数中绑定函数。
constructor (props) {
super(props);
this.add = this.add.bind(this);
this.somefunc = this.somefunc.bind(this);
}
或使用箭头符号(无需绑定)
const add = () => { /* do something */ }
const somefunc = () => { /* do something */ }
<Button
onClick={this.add}
>
+1
</Button>
更新
两个功能合二为一onClick
const doSomething = (e) => {
add();
somefunc();
}
<Button
onClick={this.doSomething}
>
+1
</Button>
我正在尝试将 2 个函数绑定到 reactjs 按钮中的同一个 onClick
事件。
我在这里看到了几个例子,但它们对我不起作用;要么语法不同,要么我的代码逻辑不支持单击一个按钮内的两个功能。这是我正在做的一个例子:
class Example extends Component {
state = {
test:1
}
//function 1
add() {
this.setState({
test: this.state.test+1
});
}
//function 2
somefunc() {
// does smthng
}
render() {
return (
<div>
<Button color = 'success'
onClick={this.add.bind(this)}>+1
</Button>
</div>
)
}
}
上面的代码有效。但是我需要能够向 onClick
添加第二个 (somefunc()
) 函数。像这样:
onClick={() => {this.add.bind(this); this.somefunc.bind(this)}}
绑定可以吗?如果没有,请您解释一下如何在没有绑定的情况下调用函数。
在构造函数中绑定函数。
constructor (props) {
super(props);
this.add = this.add.bind(this);
this.somefunc = this.somefunc.bind(this);
}
或使用箭头符号(无需绑定)
const add = () => { /* do something */ }
const somefunc = () => { /* do something */ }
<Button
onClick={this.add}
>
+1
</Button>
更新
两个功能合二为一onClick
const doSomething = (e) => {
add();
somefunc();
}
<Button
onClick={this.doSomething}
>
+1
</Button>