您应该创建一个带有两个参数的函数,然后检查以设置所需变量的状态:
handleChange: function(text, arg2) {
if(arg2 == 'gender') {
this.setState({
gender: text
});
} else if(arg2 == 'name') {
this.setState({
name: text
});
}
}
这是一个实现了功能的示例应用程序:
https://rnplay.org/apps/DX6Nrg
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
TextInput
} = React;
var App = React.createClass({
getInitialState: function() {
return {
gender: 'Gender is not yet set...',
name: 'Name is not yet set...',
};
},
handleChange: function(text, arg2) {
if(arg2 == 'gender') {
this.setState({
gender: "gender is " + text
});
} else if(arg2 == 'name') {
this.setState({
name: "name is " + text
});
}
},
render: function() {
return (
<View style={styles.container}>
<TextInput style={{backgroundColor: 'red', height:50}}
ref="gender"
onChangeText={(text) => {this.handleChange(text, 'gender')}}
placeholder="Gender" />
<TextInput style={{marginTop:10, backgroundColor: 'blue', height:50}}
ref="name"
onChangeText={(text) => {this.handleChange(text, 'name')}}
placeholder="name" />
<Text style={{marginTop:10, fontSize:20}}>{this.state.gender}</Text>
<Text style={{marginTop:10, fontSize:20}}>{this.state.name}</Text>
</View>
);
}
});
var styles = StyleSheet.create({
container: {
flex: 1,
marginTop:50
},
welcome: {
fontSize: 28,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
fontSize: 19,
marginBottom: 5,
},
});
AppRegistry.registerComponent('App', () => App);