TextInput 的 onChangeText 回調(diào)的兩種寫(xiě)法
//寫(xiě)法一
onChangeText = {(newText) => this.updateNum(newText)}
或
//寫(xiě)法二(這種寫(xiě)法和寫(xiě)法一有很多不同的地方茉继,請(qǐng)參照上邊示例代碼中寫(xiě)法2查看)
onChangeText = {this.updateNum}
里注意回調(diào)調(diào)用的寫(xiě)法,切記不可寫(xiě)成
onChangeText = {this.updateNum(newText)}
寫(xiě)法一
import React, {Component} from 'react';
import {
Platform,
StyleSheet,
View,
Text,
TextInput,
PixelRatio,
} from 'react-native';
const instructions = Platform.select({
ios: 'Press Cmd+R to reload,\n' +
'Cmd+D or shake for dev menu',
android: 'Double tap R on your keyboard to reload,\n' +
'Shake or press menu button for dev menu',
});
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
inputedNum: '',//寫(xiě)法1
};
}
updateNum(newText) {//寫(xiě)法1
this.setState((state) => {
return {
inputedNum: newText
};
});
}
render() {
return (
<View style={styles.container}>
{/*寫(xiě)法1*/}
<TextInput placeholder={'請(qǐng)輸入賬號(hào)'} onChangeText={(newText) => this.updateNum(newText)}/>
<Text>您輸入的手機(jī)號(hào):{this.state.inputedNum}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
}
});
寫(xiě)法二
import React, {Component} from 'react';
import {
Platform,
StyleSheet,
View,
Text,
TextInput,
PixelRatio,
} from 'react-native';
const instructions = Platform.select({
ios: 'Press Cmd+R to reload,\n' +
'Cmd+D or shake for dev menu',
android: 'Double tap R on your keyboard to reload,\n' +
'Shake or press menu button for dev menu',
});
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
inputedPW: ''//寫(xiě)法2
};
this.updatePW = this.updatePW.bind(this);//寫(xiě)法2
}
updatePW(newText) {//寫(xiě)法2
this.setState(() => {
return {
inputedPW: newText
};
});
}
render() {
return (
<View style={styles.container}>
{/*寫(xiě)法2*/}
<TextInput placeholder={'請(qǐng)輸入密碼'} secureTextEntry={true} onChangeText={this.updatePW}/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
}
});