简体   繁体   中英

Adding an editable prefix to the input - react

I want to add an editable prefix to the phone number input. My code looks like this

                <input
                    changeHandler={this.onInputChange}
                    errors={errors}
                    onBlur={this.onInputBlur}
                    onFocus={this.onInputFocus}
                    resetErrors={clearFieldErrors}
                    value={`+41${phoneNumber}`}/>

在此处输入图像描述

however, after adding the prefix I can't write anything in input. Does anyone know why this is happening and how to fix it?

Instead of changeHandler, you should be using onChange. See examples in https://reactjs.org/docs/forms.html#controlled-components .

Also you might use it as uncontrolled-component and give defaultValue={'+41'} too.

Instead of passing hard coded "+41" in value prop, just initialize the phoneNumber useState

Try the following code, you may find want you looking for.

export default function App() {
  const [inputPhoneNumber, setInputPhoneNumber] = React.useState('');
  const [phone, setPhone] = React.useState('+41');

  const inputChangeHandler = ({ target }) => {
    setPhone(target.value);
  };

  const submitHandler = (e) => {
    e.preventDefault();
    setInputPhoneNumber(phone);
    setPhone('+41');
  };

  return (
    <>
      <form onSubmit={submitHandler}>
        <input onChange={inputChangeHandler} value={phone} />
        <button type="submit">Submit</button>
      </form>
      <h1>{inputPhoneNumber}</h1>
    </>
  );
}

It is probably changeHandler, can you give out more code?

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