如何在onclick事件React后显示表单

Sco*_*ott 0 javascript jsx reactjs

我有一个 React 组件,它返回一个带有按钮的表单。当我单击按钮时,我希望在同一页面上显示另一个不同的表单。我怎么做?单击按钮时如何返回下一个表单?下面只是给出主要思想的一个例子

function Example() {
  return (
    <div>
      <form>
        <button onclick={showForm}></button>
      </form>
    </div>
  )
}

Run Code Online (Sandbox Code Playgroud)

Fat*_*ani 7

定义一个状态来处理表单的可见性。

import React, { useState } from 'react';

function Example() {
  const [showForm, setShowForm] = useState(false);

  const showForm = () => {
    setShowForm(!showForm);
  }

  return (
    <div>
      <form>
        <button onClick={showForm}></button>
      </form>

      {showForm && (
        <form>
          ...
        </form>
      )}
    </div>
  )
}
Run Code Online (Sandbox Code Playgroud)