[英]react/jsx-no-bind: how to pass args
I've some difficulties to understand jsx-no-bind when we've some args to pass in method. 当我们有一些传递参数的参数时,我很难理解jsx-no-bind。
My code works correctly : 我的代码正常工作:
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>
);
}
}
But I've jsx-no-bind with my linter. 但是我已经将jsx-no-bind与我的linter绑定了。
How can i use the right way with : 如何使用正确的方法:
constructor() {
super();
this.foo = this.foo.bind(this);
}
But ... in passing some args. 但是...通过了一些参数。 In my case, I want to pass "reverse" argument. 就我而言,我想传递“反向”参数。
thanks in advance, 提前致谢,
This is solved with a partial applicated function: 这可以通过部分应用的函数来解决:
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>
);
}
}
constructor() {
super();
this.foo = this.foo.bind(this);
}
This should work just fine. 这应该很好。 Later when you call this.foo( true )
or this.foo( false )
, the function will be correctly bound to the instance. 稍后,当您调用this.foo( true )
或this.foo( false )
,该函数将正确绑定到实例。
Depending on your transpiler/stack you can make use of arrow functions to make it even quicker: 根据您的编译器/堆栈,您可以使用箭头功能使其更快:
class Foo extends React.Component {
foo = ( reverse, e ) => {
// ...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.