如何将这些函数合并为具有属性的单个函数

How can I merge these functions into a single function with attributes?

本文关键字:函数 属性 单个 合并      更新时间:2023-09-26

我正在尝试将这些函数合并到一个函数中,我可以在其中传递两个属性,表单和字段。

_last_name(){
  this.refs.patient.refs.input.refs.last_name.refs.input.focus()
},
_phone(){
  this.refs.contact.refs.input.refs.phone.refs.input.focus()
},
_email(){
  this.refs.contact.refs.input.refs.email.refs.input.focus()
},
_street_address(){
  this.refs.contact.refs.input.refs.street_address.refs.input.focus()
},
_suite_or_apt(){
  this.refs.contact.refs.input.refs.suite_or_apt.refs.input.focus()
},
_city(){
  this.refs.contact.refs.input.refs.city.refs.input.focus()
},
_state(){
  this.refs.contact.refs.input.refs.state.refs.input.focus()
},
_zipcode(){
  this.refs.contact.refs.input.refs.zipcode.refs.input.focus()
},

我已经尝试过这个,但它似乎没有解决问题:

_focus_on(form, field){
  this.refs.form.refs.input.refs.field.refs.input.focus()
}

我认为这只是一个语法问题。

你几乎得到了它。如果使用括号表示法(obj[field]),则可以使用变量访问对象的属性。

_focus_on(form, field) {
  this.refs[form].refs.input.refs[field].input.focus();
}

这似乎可以解决问题:

_focusOn(form, field){
  this.refs[form].refs.input.refs[field].refs.input
}