admin管理员组文章数量:1200345
Using React-Native, I have a custom component which extends from TextInput like so:
TextBox.js
...
render() {
return (
<TextInput
{...this.props}
style={styles.textBox}/>
);
}
...
MyScene.js (imports TextBox.js)
...
render() {
render(
<View>
<TextBox
rel='MyFirstInput'
returnKeyType={'next'}
onSubmitEditing={(event) => { this.refs.MySecondInput.focus(); }}/>
<TextBox
ref='MySecondInput'/>
</View>
);
}
When I build the app and press next on the keyboard when focusing on MyFirstInput
, I expect MySecondInput
to be in focus, instead I get the error:
_this2.refs.MySecondInput.focus is not a function
What could the error be? Is it something to do with the scope of this
? Thanks.
Using React-Native, I have a custom component which extends from TextInput like so:
TextBox.js
...
render() {
return (
<TextInput
{...this.props}
style={styles.textBox}/>
);
}
...
MyScene.js (imports TextBox.js)
...
render() {
render(
<View>
<TextBox
rel='MyFirstInput'
returnKeyType={'next'}
onSubmitEditing={(event) => { this.refs.MySecondInput.focus(); }}/>
<TextBox
ref='MySecondInput'/>
</View>
);
}
When I build the app and press next on the keyboard when focusing on MyFirstInput
, I expect MySecondInput
to be in focus, instead I get the error:
_this2.refs.MySecondInput.focus is not a function
What could the error be? Is it something to do with the scope of this
? Thanks.
4 Answers
Reset to default 17This is because focus is a method of TextInput, and it is not present in your extended version.
You can add a focus method to TextBox.js as below:
focus() {
this.refs.textInput.focus();
},
and add a ref to the TextInput
render() {
return (
<TextInput
{...this.props}
ref={'textInput'}
style={styles.textBox}/>
);
}
If you wanted to do this in the modern React Version use
ref = { ref => this._randomName = ref }
If you want to access the method use
this._randomName.anyMethod()
Maybe it's because the ref doesn't return an HTML element? I don't think it has to do anything with the this scope, it just says .focus is not a function, so it can't be executed probably because .focus does not exist on a non HTML element?
MDN .focus shows that it has to be an HTML element, maybe you should log the ref MySecondInput and see if you get an element?
Other option is to pass the reference by props from TextBox.js for TextInput.
MyScene.js (imports TextBox.js)
<TextBox
refName={ref => { this.MySecondInput = ref; }}
/>
TextBox.js
<TextInput
{...this.props}
ref={this.props.refName}
... />
本文标签: javascriptReact Native this2refsmyinputfocus is not a functionStack Overflow
版权声明:本文标题:javascript - React Native _this2.refs.myinput.focus is not a function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738587468a2101514.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论