(新到反应原生( 我在屏幕中添加了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 => (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