如何设置状态(数组)并验证使用循环添加的多个文本输入 - 反应本机



(新到反应原生( 我在屏幕中添加了n TextInputs数:

  1. 需要为这些TextInputs设置状态(数组(
  2. 如何验证它们以确保它们不为空,按下按钮
renderFields(listNum) {    
    var numLists = parseInt(listNum, 10);    
    var fields = [];
    var numStr = "";
    for (let i = 0; i < numLists; i++) {
        numStr = JSON.stringify(i + 1);
        fields.push(
            <View key={i} style={styles.butInput}>
                <View style={styles.ChildViewStyle}>
                    <TextInput
                        ref={input => {
                          this.textInput = input;
                        }}
                        key={"txt_" + i}
                        style={styles.TextInputStyleClass}
                        textAlign={"left"}
                        editable={true}
                        maxLength={20}
                        defaultValue={numStr}
                    />
                </View>
            </View>
        );
    }
    return fields;
}
render() {
    const { navigation } = this.props;
    const listNum = navigation.getParam("listNum", 2);
    return (
        <View style={styles.container}>
            <View style={styles.InputContainer}>
                <ScrollView>{this.renderFields(listNum)}</ScrollView>
            </View>
            <View style={styles.settingRow}>
                <TouchableOpacity onPress={() => this.validateNum()}>
                    <Text style={styles.settingsBtnText}>S A V E</Text>
                </TouchableOpacity>
            </View>
        </View>
    );
}
Can't move further, please help

您可以按如下方式进行验证:

ref={o => (this["ref_" + i] = o(}

validateNum() {
  var isValid = true;
  this.forms.some((i,index)=> {
            if (this["ref_"+index] && !!this["ref_"+index].text() ) {
               isValid =false;
            }
        });
  return isValid;
}

要从文本输入获取文本,请创建自定义TextInput

考虑使用 redux-form 库进行验证。这比手动验证每个字段要好得多。

https://redux-form.com/8.1.0/

https://esbenp.github.io/2017/01/06/react-native-redux-form-immutable-styled-components/

https://medium.com/wolox-driving-innovation/https-medium-com-wolox-driving-innovation-easy-forms-in-react-native-with-redux-form-1cdc16a9a889

相关内容

  • 没有找到相关文章

最新更新