首页 > 解决方案 > 如何处理反应原生文本输入组件的输入验证?

问题描述

我正在尝试在我的PhoneInput组件上实现电话验证,但是在抽象级别上我有点迷茫和困惑。

我有 3 个组件的层次结构State (custom state handler) -> Phone Form (the phone form) -> Phone Input (actual phone input)

尝试的事情:

  1. PhoneInputviaonBlur()事件进行验证,无法正确获取对象 phone 值;得到[object Object]circular Dependency

  2. 将验证放入State组件中,无法使我的状态正确更改

  3. 将整个重构为一个无需使用组件即可PhoneInput处理的类,我的登录表单停止工作stateState

期望的行为:0当我输入一个以我想从电话号码中删除零开头的电话号码时。

代码:(我已经从示例中删除了所有样式表、道具和导入,但留下了我正在尝试做的事情的评论)

State.js


...omitted_code

export default class State extends React.Component<Props> {
  state = this.props.default

  update = values => {
    // [NOTE]:  2nd Try

    // const phoneValue = values.phone
    // const beginsWithZero = /^0?/

    // if (phoneValue === beginsWithZero) {
    //   const phoneFormatValue = phoneValue.replace(beginsWithZero, '')
    //   return this.setState(phoneFormatValue)
    // } else {
    //   return this.setState(values)
    // }

    this.setState(values)

    // [NOTE]: All this works, but I cannot make the state to update with phoneFormattedValue

    // console.log(`This is the value: ${JSON.stringify(values, null, 2)}`)
    // const beginsWithZero = /^0?/
    // const phoneValue = values.phone
    // const phoneFormattedValue = phoneValue.replace(beginsWithZero, '')

    // console.log(`This is the phoneValue: ${phoneValue}`)
    // console.log(`This is the phoneFormatted: ${phoneFormattedValue}`)

    // console.log(`This is the state: ${JSON.stringify(this.state, null, 2)}`)

    // formatPhoneValue = () => {}

    this.props.onChange({ ...this.state, ...values })
  }

  render() {
    const { children } = this.props

    return children(this.state, this.update)
  }
}

State.defaultProps = {
  default: {},
  onChange: () => {},
}

PhoneForm.js

..omitted_code

const PhoneForm = ({ locale, countryCode, countryCodes, style, onChange, error }: Props) => (
  <State default={{ ...DEFAULT_FORM, countryCode }} onChange={onChange}>

    //[NOTE]: the form and the update is  what I think causes me problems

    {(form, update) => (
        <LoginField style={error ? error && styles.error : false}>
          <PhoneInput
            {...form}
            countryCodes={countryCodes}
            style={loginFieldStyles.input}
            onChangeText={update}
          />
        </LoginField>
      </View>
    )}
  </State>
)

..omitted_code

电话输入.js

// [NOTE]:  1st Try: trying to handle the validation inside the component itself, would like to take that phone value from `changeText({ countryCode ,phone})` and formatted onBlur

const isValidPhoneNumber = value => {
  const phoneRegex = /^0?/

  // const phoneFormated = phone.replace(phoneRegex, '')

  // const phoneStartsWithZero = phone.startsWith('0')

  // const phoneFormated = phoneStartsWithZero ? phone.replace(phoneRegex, '') : phone

  // console.log(`${phone.startsWith('0')} starts with zero.`)



  //[NOTE]: Returns either undefined or [object Object]

  console.log('This is the value.phone', value.phone)  
  console.log('This is the value', value)
  // console.log(`This is the phone that was entered phone: ${phoneFormated}`)

  // return phoneFormated
}

type PhoneInputProps = {
...omitted_code
}

const PhoneInput = ({
...omitted_code
}: PhoneInputProps) => (
  <View style={styles.host}>

    ...omitted_code

    <RNTextInput
      ...omitted_code
      value={phone}
      onChangeText={phone => onChangeText({ countryCode, phone })}
      onFocus={phone => console.log(`I was focused, this is the phone: ${phone}`)}
      onBlur={value => isValidPhoneNumber(value)}
      {...props}
    />
  </View>
)

标签: javascriptvalidationreact-nativestatereact-native-textinput

解决方案


推荐阅读