简体   繁体   English

返回不同<input>在表单中使用开关返回输入

[英]Return different <Input> in a form using a switch to return the Input

I'm trying to achieve a Form where first you see 2 and then when you click a button, you see other Input.我正在尝试实现一个表单,首先您会看到 2,然后当您单击一个按钮时,您会看到其他输入。 I'm using a switch where based on a value I return the first 2 or the others.我正在使用一个开关,我根据一个值返回前 2 个或其他值。 I've tried returning only the, returning a form with the inputs but everything gives me the same problem.我试过只返回,返回一个带有输入的表单,但一切都给了我同样的问题。 After i fill the first two text input, when i switch to the others, the first 2 of those input has the values of the previous 2 input.在我填充前两个文本输入后,当我切换到其他文本输入时,前两个输入具有前两个输入的值。

Thanks for your help.谢谢你的帮助。

Here there is a basic version of the code这里有一个基本版本的代码

function renderSwitch() {
  switch (currentPhase) {
    case 0:
      return (
        <div>
          <input name='email' type='email' placeholder='Inserisci email' />
        </div>
      );
      break;

    case 1:
      return (
        <div>
          <input
            name='surname'
            type='text'
            placeholder='Inserisci Cognome...'
          />
        </div>
      );
      break;
  }

  return (
    <div
      className='registerpage'
      style={{ height: '100vh', backgroundColor: 'white' }}
    >
      <div className='formdiv'>
        <form onSubmit={handleSubmit}>
          {renderSwitch()}

          {currentPhase < 1 && (
            <button onClick={() => nextPhase()}>Next</button>
          )}
          {currentPhase > 0 && (
            <button onClick={() => previousPhase()}>Back</button>
          )}
          <br />
          <button type='submit'>Iscriviti</button>
        </form>
      </div>
    </div>
  );
}

You should store the input values using a state:您应该使用 state 存储输入值:

const [email, setEmail] = useState('')
const [surname, setSurname] = useState('')

function renderSwitch() {
    switch (currentPhase) {
      case 0:
        return (
          <div>
            <input value={email} name='email' type='email' placeholder='Inserisci email' />
          </div>
        );
        break;
  
      case 1:
        return (
          <div>
            <input
            value={surname}
              name='surname'
              type='text'
              placeholder='Inserisci Cognome...'
            />
          </div>
        );
        break;
    }
}

And then reset them once you have submitted your data:然后在您提交数据后重置它们:

function handleSubmit(e) {
    e.preventDefault()
    // Handler your data...

    setEmail('')
    setSurname('')
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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