gpt4 book ai didi

javascript - react /jsx-无绑定(bind): how to pass args

转载 作者:行者123 更新时间:2023-12-03 06:17:57 25 4
gpt4 key购买 nike

当我们要在方法中传递一些参数时,我很难理解 jsx-no-bind。

我的代码工作正常:

class Foo extends React.Component {
foo(reverse, e) {
if(reverse) {
//smthg to do with e.target
} else {
//smthg to do with e.target
}
// call this.bar()
}

bar() {
//smthg
}

render() {
return (
<button type="button" onClick={this.foo.bind(this, false)}>go</button>
<button type="button" onClick={this.foo.bind(this, true)}>reverse</button>
);
}
}

但是我的 linter 已经使用 jsx-no-bind 了。

我如何使用正确的方式:

constructor() {
super();
this.foo = this.foo.bind(this);
}

但是......传递一些参数。就我而言,我想传递“反向”参数。

提前致谢,

最佳答案

这是通过部分应用函数解决的:

class Foo extends React.Component {
constructor() {
super();
this.foo = this.foo.bind(this); // Bind the function as usual
}

foo(reverse, e) {
return () => { // Here you're returning a new function wrapping the original function
if(reverse) {
//smthg to do with e.target
} else {
//smthg to do with e.target
}
// call this.bar()
}
}

render() {
return (
<button type="button" onClick={this.foo(false)}>go</button> // Execute the function here with the argument
<button type="button" onClick={this.foo(true)}>reverse</button>
);
}
}

关于javascript - react /jsx-无绑定(bind): how to pass args,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39001128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com