我有一堆TextInput
字段,在表单提交时,我想突出显示留空或内容无效的字段。 (使用边框)
什么是用最少的代码处理此问题的好方法?
具有“ isEmpty”状态,该状态会在提交时进行更新,并有条件地渲染每个状态的css,这似乎有点过头了,因为存在很多字段。
是否有一种方法可以通过TextInput
或ID
来获取name
,并以React Native的方式动态更新或附加到CSS规则
答案 0 :(得分:2)
个人建议:
1-添加状态RA = (Rot) { {1, 2, 3, 4, 5}, 0 };
2-提交后,检查errors: []
的值以填充required
的自定义数据;示例:
errors
3-在您的渲染函数中,为您的onSubmit() {
let errors = []
let { firstName, lastName } = this.state
if (firstName === ''){
errors << 'firstName'
}
if (lastName === ''){
errors << 'lastName'
}
if (errors.length) {
this.setState({ errors });
return;
}
// API CALL
}
s添加一个自定义类
TextInput
现在,我当然建议将样式移至类并使用这些类,但是此示例是实现这些样式的领先方法。
我忘了提及您在文本框中编辑任何值以将边框重置为空时需要render(){
return (
<TextInput style={{ borderColor: this.state.errors.include('firstName') ? 'red' : 'transparent' }} />
)
}
。
答案 1 :(得分:0)
您可以通过本机直接操作
来执行此操作onSubmit(){
const {firstName, lastName} = this.state;
if(firstName.trim().length == 0){
this.firstNameInput.setNativeProps({
borderColor:'red',
borderWidth:1
});
return;
}
if(lastName.trim().length == 0){
this.lastNameInput.setNativeProps({
borderColor:'red',
borderWidth:1
});
return;
}
}
您的textInput看起来像
<TextInput ref={r=>this.firstNameInput=r} onChangeText={(firstName)=>this.setState({firstName})} />
<TextInput ref={r=>this.lastNameInput=r} onChangeText={(lastName)=>this.setState({lastName})} />
答案 2 :(得分:0)
您可以使用样式表来定义样式。然后根据输入的值修改样式。
import React from 'react';
import { StyleSheet, TextInput } from 'react-native';
class YourComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
username: '',
};
}
isInvalid = (input) => {
'Check if input is empty or invalid and return true if it is and false if it is not.'
}
handleUsernameInput = (input) => {
this.setState({username:text});
if(this.isInvalid(input)) {
styles.usernameInput.borderColor = '#990000';
styles.usernameInput.borderWidth = 1;
} else {
if(styles.usernameInput.borderColor) {
delete styles.usernameInput.borderColor;
delete styles.usernameInput.borderWidth;
}
}
}
render() {
return(
<View style={styles.container}>
<TextInput style={styles.usernameInput} onChangeText={(event) => this.handleUsernameInput(event)} value={this.state.username}/>
</View>
);
}
}
export default YourComponent;
const styles = StyleSheet.create({
container: {
flex: 1,
},
usernameInput: {
fontSize: 16,
padding: 15,
},
});