使用已发送变量React Native setState

时间:2015-11-18 03:46:16

标签: native react-native setstate

我想知道如何在输入字段中的文本被更改以改变特定变量时发送变量,以便我可以重用相同的函数。

var app = React.createClass({
 getInitialState: function() {
  return {
  gender: 'Male',
  name: '',
};
},
render: function() {
return (
  <View style={styles.container}>
    <TextInput style={styles.input}
      ref="gender"
      onChangeText={this.handleChange}
      placeholder={this.state.gender} />
    <TextInput style={styles.input}
      ref="name"
      onChangeText={this.handleChange}
      placeholder="name" />
  </View>
);
},
handleChange: function(text) {
  this.setState({gender: text});
}

在更改文本时,它会改变“性别”的状态。但我希望它能改变这个名字&#39;状态,如果我改变那个,都具有相同的功能。此外,我还需要添加其他字段,如果文本被更改,它将改变具有相同功能的变量的状态。

1 个答案:

答案 0 :(得分:0)

您应该创建一个带有两个参数的函数,然后检查以设置所需变量的状态:

handleChange: function(text, arg2) {
  if(arg2 == 'gender') {
    this.setState({
      gender: text
    });
  } else if(arg2 == 'name') {
    this.setState({
      name: text
    });
  }
}

Here是一个具有实施功能的示例应用程序:

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);