【问题标题】:Get TextInput Value and Checkbox state in React native在 React Native 中获取 TextInput 值和复选框状态
【发布时间】:2016-03-28 10:07:41
【问题描述】:

我想检索用户名和密码的输入值和复选框状态。我在Stackoverflow 上找到了这个相关问题。但是当尝试执行此操作时出现错误

'null' 不是对象(评估 'this.state.username')

任何人都可以帮助我检索输入值和复选框状态,因为我是 React-native 的新手

代码:

var CheckBox = require('react-native-checkbox');
var Button = require('react-native-button');

var reactnative = React.createClass({

render: function() {
 return (
  <View style={styles.container}>

    <Text style={styles.signin}>Sign In</Text>

    <TextInput style={styles.logininput} ref= "username" onChangeText={(event) => this.setState({username:event.nativeEvent.text})} value={this.state.username}/>

    <TextInput style={styles.logininput} value="Password"/>

    <CheckBox label='Remeber Me' checked = {false} onClick={this._CheckBoxState}/>

    <Button style={styles.loginButton} onPress={this._handlePress.bind(this)}>
        Login
    </Button>

  </View>
  );
 },

 _handlePress(event) {
   //Get TextInput value
    var username= this.state.username;
    alert(username);
  },

 _CheckBoxState(event){
  //want to change the state from true to false or vice-versa

  }
});

【问题讨论】:

  • 在哪里初始化初始状态?

标签: javascript checkbox react-native textinput


【解决方案1】:

您可能错过了在渲染之前初始化初始状态函数。

 ...
 getInitialState: function() {
    return {username: ''};
 },
 render: function() {
  ....
 }

现在 this.state.username 应该可以访问了。

【讨论】:

  • 感谢这解决了我检索输入值的问题。 :) 你能帮我获得复选框状态吗?
  • 与任何输入的原理相同。您可以在复选框上应用 onChange 事件。并将其连接到当前复选框状态被否定的函数。所以在设置状态-> checkboxIsSelected:!this.state.checkBoxIsSelected。当然,您还必须将 checkboxIsSelected 添加到您的初始状态
猜你喜欢
  • 2021-08-19
  • 2021-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-07
  • 1970-01-01
相关资源
最近更新 更多