简体   繁体   English

在 react js 中渲染新组件 onClick 的方法

[英]Way to render a new component onClick in react js

Am trying to render a new component onclick a button in react js.我正在尝试在 React js 中单击一个按钮来渲染一个新组件。 Am using functional components and I can't handle it.我正在使用功能组件,我无法处理它。 Eg: am in the UserManagement component and on a button click I need to render another component named employee management.例如:在 UserManagement 组件中,单击按钮我需要呈现另一个名为员工管理的组件。

You can conditionally render your component.您可以conditionally地渲染您的组件。

Example :例子 :

EmployeeManagement.js EmployeeManagement.js

const EmployeeManagement = () => {
   ....

   return (
    <div>
      EmployeeManagement
    </div>
  );
}

UserManagement.js用户管理.js

const UserManagement = () => {
   const [hasRender, setRender] = useState(false);
   const onShow = React.useCallback(() => setRender(true), []);


   return (
     <>
      <button onClick={onShow}>Show Employee Management</button>
      {hasRender && <EmployeeManagement />}
    </>
   )
}

use a visible state & toggle it in onClick:使用可见状态并在 onClick 中切换:

const [visible, setVisible] = useState(false)

onClick = () => {setVisible(true)}

then render it like this:然后像这样渲染它:

{visible && <EmployeeManagement onClick={onClick} />}

One way to do this would be to add a local state in UserManagement ,一种方法是在UserManagement添加本地状态,
that holds a boolean value indication whether the component should be hidden or shown.它保存一个boolean值,指示组件是隐藏还是显示。

Then you will have something like:然后你会有类似的东西:

function UserManagement() {
   const [compIsShown, setCompIsShown] = useState(false);

   return (
      // Whatever else you're rendering.
      <button onClick={() => setCompIsShown(true)}>...</button>
      {compIsShown && <OtherComp />}
   )
}

What will happen is that compIsShown will initialize as false,将会发生的是compIsShown将初始化为 false,
so this condition compIsShown && <OtherComp /> will prevent it from rendering.所以这个条件compIsShown && <OtherComp />会阻止它渲染。
Then, when you click the button, the state will set, causing a re-render, except now the condition will be true, so <OtherComp> will be rendered.然后,当您单击按钮时,将设置状态,导致重新渲染,但现在条件为真,因此<OtherComp>将被渲染。

There are other ways to go about this.还有其他方法可以解决这个问题。
Depends mostly on the use-case.主要取决于用例。

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

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