[英]react-native onChangeText this.value is undefined
I am adding simple masking to a text input, so the date in my DOB field looks like DD/MM/YYYY. 我在文本输入中添加了简单的遮罩,因此DOB字段中的日期看起来像DD / MM / YYYY。
I have a function to handle that: 我有一个函数来处理:
dateFormat(text) {
if (text.match(/^\d{2}$/) !== null) {
this.value = text + '/';
} else if (text.match(/^\d{2}\/\d{2}$/) !== null) {
this.value = text + '/';
}
this.setState({birthdate: this.value});
}
I call this function with: 我称这个功能为:
onChangeText={(text) => this.dateFormat(text)}
The text is passed correctly. 文本正确传递。 However, this.value is undefined and setting it to whatever, makes no difference.
但是,未定义this.value并将其设置为任何值都没有区别。
What I am doing wrong? 我做错了什么?
I don't think you need to reference it as this.value, just declare a var value = text: 我认为您无需将其引用为this.value,而只需声明var value = text:
onChangeText(text){
if (text.match(/^\d{2}$/) !== null) {
var value = text + '/';
this.setState({birthdate: value})
} else if (text.match(/^\d{2}\/\d{2}$/) !== null) {
var value = text + '/';
this.setState({birthdate: value});
} else {this.setState({birthdate:text})}
}
I've set it up on RNPlay here , and is seems to be working fine: 我已经在RNPlay上对其进行了设置 ,并且似乎运行良好:
https://rnplay.org/apps/O9a7XQ https://rnplay.org/apps/O9a7XQ
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
TextInput
} = React;
var SampleApp = React.createClass({
getInitialState(){
return {
birthdate: ''
}
},
onChangeText(text){
if (text.match(/^\d{2}$/) !== null) {
var value = text + '/';
this.setState({birthdate: value})
} else if (text.match(/^\d{2}\/\d{2}$/) !== null) {
var value = text + '/';
this.setState({birthdate: value});
} else {this.setState({birthdate:text})}
},
render: function() {
return (
<View style={styles.container}>
<TextInput
value={this.state.birthdate}
onChangeText={ (text) => this.onChangeText(text) }
style={styles.textInput}
/>
<Text>{this.state.birthdate}</Text>
</View>
);
}
});
var styles = StyleSheet.create({
container: {
flex: 1,
marginTop:60
},
textInput: {
height:70,
backgroundColor: '#ddd'
}
});
AppRegistry.registerComponent('SampleApp', () => SampleApp);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.