如何设置状态(数组)并验证使用循环添加的多个 TextInputs - react native
how to set state (array) and validate multiple TextInputs added using a loop - react native
(react-native 的新手)我在屏幕中添加了 n
个 TextInputs
:
- 需要为这些
TextInputs
设置状态(数组)
- 如何在按下按钮时验证它们以确保它们不为空
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://esbenp.github.io/2017/01/06/react-native-redux-form-immutable-styled-components/
(react-native 的新手)我在屏幕中添加了 n
个 TextInputs
:
- 需要为这些
TextInputs
设置状态(数组) - 如何在按下按钮时验证它们以确保它们不为空
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://esbenp.github.io/2017/01/06/react-native-redux-form-immutable-styled-components/