【问题标题】:How to wait validate component when i call a function in React native?当我在 React Native 中调用函数时如何等待验证组件?
【发布时间】: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


    【解决方案1】:

    你可以使用 async 和 await

    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= async(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;
    

    在需要的地方使用 await

    【讨论】:

    • 在 setSubmit() 中等待?
    【解决方案2】:

    我必须定义一个值来设置指定验证的结果,例如 (setIsValidEmail):

    <Validator typeValidate={()=>ValidatorType.Email(email)} value={email} setResult={resp=> setIsValidEmail(resp)} visible={enabledValidator} />
    

    在函数中我要求结果:

     if(isValidEmail)
     {...do something}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-31
      • 1970-01-01
      • 2019-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多