如何设置状态(数组)并验证使用循环添加的多个 TextInputs - react native

how to set state (array) and validate multiple TextInputs added using a loop - react native

(react-native 的新手)我在屏幕中添加了 nTextInputs

  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 => (这个["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 获取文本,请创建自定义 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