如何在点击按钮时呈现不同的组件

时间:2020-04-19 10:06:49

标签: javascript reactjs

我的UI上有几个按钮,单击时我想使用react将相应的组件加载到它们,我不知道该怎么做。

我以前使用三元运算符来执行此操作,但是它仅适用于两个组件,这里我有两个以上的组件。

在点击每个后端时,我有5个按钮,然后在UI上呈现内容。

Please check the code sandbox for all code

单击按钮时,我必须渲染组件并且这些组件具有不同的UI如果所有组件都具有相同的数据格式和相同的UI,我可以使用useState来完成此操作,但是这里需要加载组件

3 个答案:

答案 0 :(得分:2)

首先,您的组件User, Admin and Client中存在一些错误:它们在文件中具有相同的名称。 您可以像这样轻松地解决您的问题:

import React, { useState } from "react";
import Buttons from "./Components/side_btns";
import { Admin, Client, User } from "./Components";
import "bootstrap/dist/css/bootstrap.min.css";
import "./styles.css";

const App = () => {
  const [activeTab, setActiveTab] = useState("");

  const onSideBtnClick = e => {
    console.log(e.target.value);
    setActiveTab(e.target.value);
  };

  return (
    <div className="App">
      <div className="row">
        <div className="col-5 col-sm-5 col-md-3 col-lg-2 col-xl-2">
          <Buttons trigerOnClickEmpSideBtn={onSideBtnClick} />
        </div>
        <div className="col-7 col-sm-7 col-md-9 col-lg-10 col-xl-10" />
        {activeTab === "admin" && <Admin />}
        {activeTab === "user" && <User />}
        {activeTab === "info" && <Client />}
      </div>
    </div>
  );
};
export default App;

这里是example

答案 1 :(得分:1)

我只是使用字典方法来使用按钮值来渲染组件。您可以检查codesandbox

const dynamicComponents = () => {
  const components = {
    admin: <Admin />,
    info: <Client />,
    user: <User />
  };

  return components[componentName];
};

答案 2 :(得分:0)

保持tabactive的状态并在它们之间切换,例如:

          {tabactive == 1 ? (
            <Admin />
          ) : tabactive == 2 ? (
            <User  />
          ) : tabactive == 3 ? (
            <Security />
          ) : tabactive == 4 ? (
            <Profile />
          ) : null}
相关问题