如何在React Native中验证动态表单



因此,首先,我初始化所需计数的空状态(如果用户输入为5并提交,我将用5状态初始化空状态(,

然后通过使用这个,我正在循环创建动态表单(正在使用map(,现在如何验证表单!

我的初始状态形成:

state = {usersDetails: []};
componentDidMount(){
this.setInitialRow()
}
setInitialRows(){
const seats = this.props.selectedSeats;
let newRow = [];
for(let i=0;i<seats.length;i+=1){
newRow.push(
{"seatName": seats[i].name,
"passenger": [{
"name":"",
"gender": "",
}]
})
}
this.setState({usersDetails: newRow})
}

因此,从上面,我得到了我的状态,通过使用这个,我以这种方式循环:

{this.state.usersDetails.map((s, i) =>{
<TextInput 
style={{ borderBottomWidth: 1, borderColor: '#f0eff4', height: 40 }}
placeholder="Enter Name"
onChangeText={(text) => this.handleNameChange(text,i)}
/>
<TextInput 
style={{ borderBottomWidth: 1, borderColor: '#f0eff4', height: 40 }}
placeholder="Enter Age"
onChangeText={(text) => this.handleAgeChange(text,i)}
/>
}

所以,根据这个,我将得到5双以上!现在如何验证每对上的输入字段?

我试过这个:

handleSubmit(){
let row = this.state.usersDetails;
function isNameEmpty(r){
return r["passenger"][0].name === ''
}
function isAgeZero(r){
return r["passenger"][0].age == 0
}

let isNameFail = row.find(isNameEmpty)
let isAgeFail = row.find(isAgeZero)
if(isNameFail || isAgeFail){
// ToastAndroid.show('Please fill the Passenger Details',0.2)
}else{
console.log(row);
}
}

通过此功能,我收到吐司警告!但是,如何在相应的文本输入下显示错误消息?

这可能有助于了解如何实现

class App extends Component {

componentDidMount() {
this.getDynamicInputs();
}
state = { userDetails: [], item_views: [], errorViews: [] };
updateState = (index, value) => {
const userDetails = [...this.state.userDetails]; //make a copy of array
userDetails[index] = value;
this.setState({ userDetails: userDetails });
};
getDynamicInputs() {
const inputData = [];
const errorViews = [];  
for (let i = 0; i < count; i++) {
inputData.push(
<>
<TextInput
key={i}
style={{ borderBottomWidth: 1, borderColor: "#f0eff4", height: 40 }}
placeholder="Enter Name"
onChangeText={(val) => this.updateState(i, val)}
value={this.state.userDetails[i]}
/>
{ this.state.errorViews[i] && this.state.errorViews[i].error ? <Text>Required Field</Text> : null}
</>
);
errorViews.push( { error: false } );
}
this.setState({ item_views: inputData, errorViews: errorViews });
}
validate(){
const errorViews = _.clone(this.state.errorViews); 
for (let i = 0; i < count; i++) {    
if( this.state.userDetails[i] === “” ){
errorViews[i].error = true;
}
}
this.setState({errorViews});
}
render() {
console.log(this.state.userDetails);
return <View style={styles.app}>
{this.state.item_views}
<Button onPress={() => this.validate()}>Validate</Button>    
</View>;
}
}
const styles = StyleSheet.create({
app: {
flex: 1,
backgroundColor: "pink"
}
});
export default App;

最新更新