如何使用 Material UI 在 React 中打开新组件

问题描述 投票:0回答:1

我正在使用 Typescript 和 Material UI 在 React 中创建一个仪表板,其中包含月份以及除月份之外还显示的相应值。为此,我使用了我创建的“仪表板”React 组件。单击特定月份后,我想打开另一个视图(组件)以向用户显示一些不同的信息。我怎样才能做到这一点?这是到目前为止我的组件的代码。具体来说,我想知道如何更新 handleMonthClick 方法以在选择月份时打开新视图。

import React from 'react';
import MonthCard from './MonthCard';

const Dashboard: React.FC = () => {
  const months = [
    { month: 'January', passRate: 80 },
    { month: 'February', passRate: 75 },
    // Add more months as needed
  ];

  const handleMonthClick = (month: string) => {
    console.log(`Clicked on ${month}`);
    // You can add more logic here
  };

  return (
    <div>
      <h1>Dashboard</h1>
      {months.map((m) => (
        <MonthCard
          key={m.month}
          month={m.month}
          passRate={m.passRate}
          onClick={() => handleMonthClick(m.month)}
        />
      ))}
    </div>
  );
};

export default Dashboard;

reactjs typescript material-ui react-router
1个回答
0
投票

您可以创建一个状态变量,将该状态变量设置为所选月份,然后根据所选月份渲染一些其他组件。

例如:

const Dashboard: React.FC = () => {
  const [selectedMonth, setSelectedMonth] = useState(null);

  const months = [
    { month: 'January', passRate: 80 },
    { month: 'February', passRate: 75 },
    // Add more months as needed
  ];

  const handleMonthClick = (month: string) => {
    console.log(`Clicked on ${month}`);
    setSelectedMonth(month);
    // You can add more logic here
  };

  return (
    <div>
      <h1>Dashboard</h1>
      {months.map((m) => (
        <MonthCard
          key={m.month}
          month={m.month}
          passRate={m.passRate}
          onClick={() => handleMonthClick(m.month)}
        />
      ))}

      {selectedMonth && <MyMonthDisplay month={selectedMonth} />}

    </div>
  );
};

现在创建一个新组件

MyMonthDisplay.jsx
,用于显示传入的
month
参数的信息。

© www.soinside.com 2019 - 2024. All rights reserved.