【问题标题】:How do I implement conditional rendering in a functional React component?如何在功能性 React 组件中实现条件渲染?
【发布时间】:2022-01-05 20:03:42
【问题描述】:

我想在功能性 React 组件中实现条件渲染。我不知道如何在函数中执行此操作。

我需要根据状态来渲染对应的导入组件。

我使用三元运算符编写了这个逻辑,一切正常,但是这段代码很糟糕而且不可读。

import React, { useState, useEffect } from "react";

import Header from "./header/header";
import Footer from "./footer/footer";

// One of these components will be rendered between Header and Footer ↓
// Name of the component in the state (activeItem)

import Landing from "./landing/landing";
import BookingManagement from "./bookingManagement/BookingManagement";
import BookingTickets from "./bookingTickets/bookingTickets";
import EnterProfile from "./enterProfile/enterProfile";
import PersonalArea from "./personalArea/personalArea";
import Register from "./register/register";
import SearchResults from "./searchResults/searchResults";
import ChoosePlace from "./choosePlace/choosePlace";

function App() {
  const [activeItem, setActiveItem] = useState("landing");

  useEffect(() => {
    console.log(activeItem);
  });

  return (
    <>
      <Header changeMain={setActiveItem} />
      {activeItem == "landing" ? <Landing changeMain={setActiveItem} /> : <></>}

      {activeItem == "bookingManagement" ? <BookingManagement /> : <></>}
      {activeItem == "bookingTickets" ? <BookingTickets /> : <></>}
      {activeItem == "enterProfile" ? <EnterProfile /> : <></>}
      {activeItem == "personalArea" ? <PersonalArea /> : <></>}
      {activeItem == "register" ? <Register /> : <></>}
      {activeItem == "searchResults" ? <SearchResults /> : <></>}

      {activeItem == "choosePlace" ? <ChoosePlace /> : <></>}

      <Footer changeMain={setActiveItem} />
    </>
  );
}

export default App;

我肯定需要在功能组件中实现这个,因为我使用了钩子。

【问题讨论】:

  • 为什么不将字符串映射到组件?
  • 看起来你可能正在寻找React Router

标签: javascript reactjs render


【解决方案1】:
function App() {
    
    const [activeItem, setActiveItem] = useState('landing');
    
    const itemToComponent = [
      landing: {component: Landing},
      bookingManagement: {component: BookingManagement},
      ...
    ]
    const Components = itemToComponent[activeItem].component
    
  return (
    
      {<Components />}
          <Footer changeMain={setActiveItem}/>
       </>
  );
}

export default App;

【讨论】:

  • 欢迎来到 Stack Overflow。当代码附有解释时,它会更有帮助。 Stack Overflow 是关于学习的,而不是提供 sn-ps 来盲目复制和粘贴。请edit您的问题并解释它如何回答所提出的具体问题。见How to Answer
【解决方案2】:

您可以创建一个包装所有组件的对象,然后通过使用 activeItem 作为键来使用正确的组件:

    import React, {useState, useEffect} from 'react';

    import Header from './header/header';
    import Footer from './footer/footer';

    import Landing from './landing/landing';
    import BookingManagement from './bookingManagement/BookingManagement';
    import BookingTickets from './bookingTickets/bookingTickets';
    import EnterProfile from './enterProfile/enterProfile';
    import PersonalArea from './personalArea/personalArea';
    import Register from './register/register';
    import SearchResults from './searchResults/searchResults';
    import ChoosePlace from './choosePlace/choosePlace';

    const components = { Landing, BookingManagement, BookingTickets, EnterProfile, PersonalArea, Register, SearchResults, ChoosePlace };

    export default function App() {
      const [activeItem, setActiveItem] = useState("Landing");
      const ActiveItemComponent = components[activeItem];

      return (
        <>
          <Header changeMain={setActiveItem} />
          <ActiveItemComponent />
          <Footer changeMain={setActiveItem} />
        </>
      );
    }

【讨论】:

    【解决方案3】:

    而不是

    {(activeItem=='landing' ? (
        <Landing changeMain={setActiveItem}/>
      ) : (
        <></>
      ))}
    

    一起去

    {activeItem=='landing' && (
        <Landing changeMain={setActiveItem}/>
    )}
    

    【讨论】:

    • 虽然这省略了三元运算符条件渲染中:(else)部分的需要,但它很难解决核心问题,即重复语句。简单地拥有一个组件的映射并让activeItem 成为决定要渲染哪个组件的索引要干净得多。
    • 你是对的!谢谢你的评论?
    【解决方案4】:

    您可以使用 react-router 实现。或者如果你想在这个组件中处理相同的事情,你可以像下面这样做类似的事情

    const getComponent = () => {
      if (condition1) {
        return <Component1/>
      } else if (condition2) {
        return <Component2/>
      }
     
      return <DefaultComponent/>
    }
    

    在渲染返回中,您可以像下面这样调用该函数

    return (
      {getComponent()}
    )
    

    【讨论】:

      【解决方案5】:

      怎么样

      const ComponentMap = {
        landing: Landing,
        bookingManagement: BookingManagement,
        bookingTickets: BookingTickets,
        enterProfile: EnterProfile,
        personalArea: PersonalArea,
        register: Register,
        searchResults: SearchResults,
        choosePlace: ChoosePlace
      };
      
      function App() {
        const [activeItem, setActiveItem] = useState("landing");
      
        useEffect(() => {
          console.log(activeItem);
        });
      
        const ActiveComponent = ComponentMap[activeItem] || React.Fragment;
        const ActiveComponentProps = {};
        if (activeItem === "landing") {
          ActiveComponentProps.changeMain = setActiveItem;
        }
        
        return (
          <>
            <Header changeMain={setActiveItem} />
            <ActiveComponent {...ActiveComponentProps} />
            <Footer changeMain={setActiveItem} />
          </>
        );
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-01
        • 2019-03-24
        • 1970-01-01
        • 2021-09-02
        • 2021-06-07
        • 2021-06-08
        • 1970-01-01
        • 2018-02-17
        相关资源
        最近更新 更多