传递其他参数来绑定? [英] Pass additional parameters to bind?

查看:46
本文介绍了传递其他参数来绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个看起来像这样的函数:

I have two functions that look like this:

  primaryImageLoaded () {
    this.setState({primaryImageLoaded: true})
  }

  secondaryImageLoaded () {
    this.setState({ secondaryImageLoaded: true })
  }

他们被这样调用(使用反应):

They are called like this(using react):

onLoad={this.secondaryImageLoaded.bind(this)

这感觉过度,我想只有一个函数并将状态变量作为参数传递,但是如何将其他参数传递给 .bind ?是否可以在我传递给 setState 的对象中使用变量作为键?

This feels excessive and I would like to have just one function and pass the state-variable as a parameter, but how can I pass an additional argument to .bind? and is it possible to use a variable as key in the object i'm passing to setState?

推荐答案

您可以将其他参数传递给将在调用函数时传递的绑定:

You can pass additional arguments to bind that will be passed when your function is invoked:

this.secondaryImageLoaded。 bind(this,arg1,arg2)

如果您使用ECMAScript 2015及更高版本,则可以使用变量作为键,将其包装在方括号中:

If you are using ECMAScript 2015 and onwards, you can use a variable as a key by wrapping it in square brackets:

this.setState({
    [myVar]: value
});

所以你可以把它改写成更像:

So you could rewrite it to be more like:

function imageLoaded(which) {
    this.setState({
        [which]: true
    });
}

onLoad={this.imageLoaded.bind(this, 'secondary')}

这篇关于传递其他参数来绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆