首页 > 解决方案 > reactjs条件渲染在第二次点击后工作

问题描述

我有三个组件:MyDashboard、MyContent、MyForm。

MyDashboard 组件首先将 MyContent 组件呈现为子组件。我在 MyContent 组件中有一个按钮,单击该按钮应将组件与 MyForm 组件交换。

单击按钮会在第一次单击时闪烁 MyForm 组件,然后直接返回 MyContent 组件。然而,在第二次单击后,MyForm 组件被呈现并保持呈现。

我的仪表板:

function MyDashboard(props) {
  const [viewForm, setViewForm] = useState(false); // Don't show the form initially

  const handleClick = () => {
    setViewForm(!viewForm);
  };

  return (
    <div>
            {(() => {
              if (viewForm) { // conditionally render the form or the content
                return <MyForm {...props} />;
              } else {
                return (
                  <MyContent
                    {...props}
                    setViewForm={handleClick}
                    viewForm={viewForm}
                  />
                );
              }
            })()}
    </div>
  );
}

我的内容:

function MyContent(props) {

  return (
    <p>
        <a href="#" onClick={props.setViewForm}> // need to click this twice to render the form.
          Show the form
        </a>
    </p>
  );
}

export default MyContent;

我的表格:


function MyForm({ props, location }) {

// form setup 


  return (
    <div>
      <Row>
        <Form>
         //... the form
        </form>
      </Row>
    </div>
  );
}

export default MyForm;

标签: reactjsweb-component

解决方案


推荐阅读