简体   繁体   中英

how to set button disable in certain condition in react?

import PhoneInput, { formatPhoneNumber, formatPhoneNumberIntl, isValidPhoneNumber } from 'react-phone-number-input';

const [fields, setFields] = React.useState([{ value: null }]);

<PhoneInput
  id="phoneNumbers1"
  type="text"
  placeholder="Enter phone number "
  value={field.value || ""}
  defaultCountry="US"
  international
  name="phoneNumbers"
  error={disable}
  autoComplete='off'
  onBlur={formik.handleBlur}
  onChange={(e) => handleChange(idx, e)}
  onClick={() => setIndex(idx)}
/>
<button
  type="button"
  hidden={fields.length > 1}
  data-value={fields.length}
  disabled={!fields[0]?.value && !(isValidPhoneNumber(fields[0]?.value ||''||fields.length<10))}
  onClick={() => handleAdd()}
>
  + Phone
</button>

Inside button inside disable property if I try to give condition that button is disabled until user give 10 digit phone number with condition field.length < 10 . It throws an error "TypeError: A text for parsing must be a string." What should be the condition inside disable attribute that until user give 10 digit phone number button should disable?

If I had to guess here, it seems isValidPhoneNumber may be expecting a string value, but if fields[0]?.value is falsey, and '' is obviously falsey, the boolean fields.length < 10 value is passed. I suspect you want this last condition outside of the isValidPhoneNumber validator function. I also suspect you want to check the length of the value, not the length of the fields array.

disabled={
  !isValidPhoneNumber(fields[0]?.value || "") ||
  fields[0]?.value?.length < 10
}

编辑 how-to-set-button-disable-in-certain-condition-in-react

I think the last condition is checking the length of array instead the length of the first value of the fields array ie fields[0].value .

Try to use

disabled={?fields[0].?value &&.(isValidPhoneNumber(fields[0]?.value ||''||fields[0]..value.length<10))}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM