【发布时间】:2021-09-23 23:51:57
【问题描述】:
我正在尝试为 React native 中的输入实现我自己的验证器组件,我的组件接收一个类型的函数来验证,setFunction 用于 set("return") 结果和一个用于知道是否启用的属性。
Validator.tsx
const OnlyNumbers=(value:any, message:string="Error number format")=>{
let match=false;
if(typeof value =="number")
match=true;
if(typeof value=="string")
match= /^[0-9]*$/.test(value);
return match ? '' : message;
}
const Email=(value:string, message:string="Error email format" ):string=>{
let match=false;
match= /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/.test(value);
return match ? '' : message;
}
const Validator=(props)=>{
const {setResult, typeValidate, enable=true , defStyle={color:'red', fontSize:15}} = props;
const [text, setText] = useState('');
useEffect(()=>{
if(enable){
//to invoke received function validate
let sms = typeValidate()
setText(sms)
//returns if exists an error
setResult(sms.length>0)
}
}, [enable, setResult])
return(
<>
{enable && text.length>0 ? <Text style={defStyle}>{text}</Text>:null}
</>
);
}
export const ValidatorType={
OnlyNumbers,
Email,
}
export default Validator;
实施.tsx
import Validator, {ValidatorType} from '../Components/Validator'
const Implementation=(props)=>{
const [email, setEmail] = useState('');
const [telephone, setTelephone] = useState('');
const [submit, setSubmit] = useState(false);
const [errorForm, setErrorForm] =useState(false);
async function RegisterTaster(){
setSubmit(true)
if(!errorForm){
//do something.....
}
}
return(
<View>
<TextInput placeholder="Email..." defaultValue={email} onChangeText={txt=> setEmail(txt)} style={Styles.txtInputs} />
<Validator typeValidate={()=>ValidatorType.Email(email)} setResult={resp=> setErrorForm(resp)} enable={submit} defStyle={Styles.txtInputsError} />
<TextInput placeholder="Telephone..." defaultValue={telephone} onChangeText={txt=> setTelephone(txt)} style={Styles.txtInputs} />
<Validator typeValidate={()=>ValidatorType.OnlyNumbers(telephone)} setResult={resp=> setErrorForm(resp)} defStyle={Styles.txtInputsError} />
<Button primary style={Styles.btnRegister} onPress={async ()=> await RegisterTaster() }>
<Text style={Styles.txtRegister}>Register</Text>
</Button>
<View>
)
}
实际上在 RegisterTaster() 中,我首先将 submit 设置为 true 以在每个验证器中 更新 enable prop;我想在那一刻如果存在错误,Validator update errorForm然后继续下一个如果知道是否做某事......
如何等到验证器更新 errorForm 后再评估下一个?
【问题讨论】:
标签: reactjs react-native asynchronous react-hooks use-effect