【问题标题】:React-Native: Cannot set state from form valuesReact-Native:无法从表单值设置状态
【发布时间】:2016-08-27 13:28:29
【问题描述】:

我正在尝试使用 tcomb-form-native 组件在 React-Native 中构建一个简单的登录表单。我创建了用于将值设置为初始状态的方法 handleChange 和用于提交的 handleForm。现在使用我的代码,当我在输入字段中输入内容时,内容被删除并替换为占位符(无控制台输出),当我按下提交按钮时,我收到错误“未定义不是对象(评估这个.refs.form)”。有没有更好的方法呢?

这是我导入和设置所有内容的方式:

import React, { Component } from 'react';

import {
  Text,
  View,
  StyleSheet,
  TextInput,
  TouchableHighlight,
  ActivityIndicator,
  Image
} from 'react-native';

var t = require('tcomb-form-native');

var Form = t.form.Form;

var User = t.struct({
  username: t.String,
  password: t.String
});

var options = {
  auto: 'placeholders',
  fields: {
    password: {
        password: true
    }
  }
};

这是我的类和方法:

class Login extends Component {
constructor(props) {
    super(props);
    this.state = {
        value: {
            username: '',
            password: ''
        },
        isLoading: false,
        error: false
    };
    this.handleChange.bind(this);
}
handleChange(value) {
    this.setState({value});
}
handleSubmit() {
    var value = this.refs.form.getValue();
    //update the indicator spinner
    this.setState({
        isLoading: true
    });
    console.log(value);
}

这就是我渲染一切的方式:

render() {
    return (
        <View style={styles.mainContainer}>
            <View style={styles.logo}>
                <Image source={require('../icon.png')} />
            </View>
            <Text style={styles.title}>Login</Text>
            <Form
                ref={(f) => this.form = f}
                type={User}
                options={options}
                onChangeText={(value) => this.setState({value})}
                value={this.state.value}
            />
            <TouchableHighlight
                style={styles.button}
                onPress={this.handleSubmit}
                underlayColor="white">
                    <Text style={styles.buttonText}>LOGIN</Text>
            </TouchableHighlight>
        </View>
    );
}

【问题讨论】:

    标签: javascript forms reactjs react-native


    【解决方案1】:

    Don't Use Bind When Passing Props

    那么你可以这样做

    onPress={this.handleSubmit}
    
    handleSubmit = () => {...}
    

    【讨论】:

    • 非常感谢您的回答,但不幸的是我无法测试它,因为我无法修复 handleChange,目前我在输入字段中添加的所有内容都会自动删除并显示占位符...我尝试使用与上面相同的原理,但看起来并非如此。
    • 我已经用我最后的更改修改了上面的代码。看起来它不再删除它们,但我的模拟器现在停止工作,所以我还没有控制台来测试它。
    • 我管理,文本的问题是我绑定到一个空变量,你的回答帮助我理解 onPress 方法。感谢您的帮助!
    【解决方案2】:

    TouchableHightlight中,需要定义:onPress={this.handleSubmit}为:

    onPress={() =&gt; this.handleSubmit()}

    onPress={this.handleSubmit.bind(this)}

    此外,ref 现在在 React (+ Native) (https://facebook.github.io/react/docs/more-about-refs.html#the-ref-string-attribute) 中不应该是字符串,而是例如:

    ref={(f) =&gt; this.form = f}

    然后你用this.form引用它。

    【讨论】:

      猜你喜欢
      • 2021-06-03
      • 1970-01-01
      • 2021-04-27
      • 1970-01-01
      • 1970-01-01
      • 2023-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多