[英]React native: invoke method dynamically
如何在Javascript中调用动态命名的方法。
我正在使用React Native
,当在TextInput
分配ref
,我需要设置动态方法。
renderInput(id) {
<TextInput
ref={(input) => this.myInput = input}
/>
}
我需要动态this.myInput
。
我测试了它并且弄错了: this.myInput[id]
和this[id].myInput
你应该使用当前 :
this.myInput.current[id]
这是如何做:
// First, create a reference (in the constructor)
this.myInput = React.createRef()
// Then, assign the ref (in the element)
<TextInput ref={this.myInput} />
// Now, to access the reference
// this.myInput.current.<<property you wanted to access>>
this.myInput.current[id] // id is defined as a variable
// this will get the dom id
// this.myInput.current.id
但是如果你坚持使用像你现在一样的回调参考,那么你可以通过id道具:(另外,我认为你正在寻找的答案是)
renderInput(id) {
<TextInput
ref={(input) => this.myInput = input}
id={id} {/* you were missing this in fact */}
/>
}
现在,要获得该ID:
this.myInput.id // will work fine, coz we have id prop now
// gets DOM id that you assigned in your element
constructor(props) {
super(props);
this.inputs = {};
}
// params Object should be in this format {id:324, referenceKey: 'one'};
renderTextInput(params) {
return <TextInput ref={input => { this.inputs[params.referenceKey] = input }}/>
}
//使用推荐
componentDidMount(){
this.inputs['one'].focus()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.