是否可以在 React 中使用模板文字作为组件名称?

Is it possible to use Template literal for Component name in React?

这可能很奇怪,但我想在 ReactJs 中动态路由。因此,我尝试使用模板文字来生成组件名称,但它不起作用。知道它是怎么做到的吗?还是不允许?

<Routes>
{
    Object.keys(Nav_items).map((key,index)=>{
    <Route path={`/${pageNav[key]}`} exact element={<`$(pageNav[key])`/>} ></Route>)
}
<Route path={'/home'}  exact element={<HomePage/>} ></Route>
</Routes>

更新:包括整个文件

import './Navbar.css'
import {Route, Routes, Link} from 'react-router-dom'
import ElectronicsPage from '../SubPages/ElectronicsPage/ElectronicsPage'
import FashionPage from '../SubPages/FashionPage/FashionPage'
import BestPage from '../SubPages/BestPage/BestPage'
import FurnituresPage from '../SubPages/FurnituresPage/FurnituresPage'
import GamingPage from '../SubPages/GamingPage/GamingPage'
import GroceriesPage from '../SubPages/GroceriesPage/GroceriesPage'
import HomeAppliancesPage from '../SubPages/HomeAppliancesPage/HomeAppliancesPage'
import Mainpage from '../Homepage/MainPage'
import HomePage from '../Homepage/Homepage'


const Navbar=()=>{


    let Nav_items={"Best Sellers":["Redmi Note 7 Pro", "Mac Pro 2","LG TV 5", "Airtel Data Card"],
                "Electronics":["Mobiles","Laptops","Accessories","Smart Devices"],
                "Fashion":["Men's Casual wear","Women's Casual wear","Men's Formal wear", "Children's wear","Accessories"],
                "Gaming":["Gaming Laptops","Build PCs","Gaming Mobiles","Controllers","Games"],
                "Home Appliances":["TVs","Washing Machines","Refrigerators","Ovens","Air Conditioners","Water Purifiers"],
                "Furnitures":["Tables and Desks","Sofas and Chairs","Wardrobes","Beds and Mattresses","Chimneys and Kitchen set"],
                "Groceries":["Vegetables","Masala items","Instant foods","Cosmetics","Hygiene Products"]
            }
        
    const pageNav={"Best Sellers":"BestPage","Electronics":"ElectronicsPage","Fashion":"FashionPage","Gaming":"GamingPage",
                "Home Appliances":"HomeAppliancesPage","Furnitures":"FurnituresPage","Groceries":"GroceriesPage"}

    
    
    return(
        <div>
        <div data-TestId="nav" className="navbar">
            <Link to={'/home'}><img className="option" src={"./option-button.png"} alt="option-button"/></Link>
            {
                Object.keys(Nav_items).map((key,index)=>
                <div className="nav-button">
                    <Link to={`/${pageNav[key]}`}><button>{key}</button></Link>
                    
                <div className="dropdown">
                    {
                    Nav_items[key].map((k,index)=><div className="dropdown">
                    <button>{k}</button></div>)
                    }
                </div>
                </div>
                )
            }
            </div><div style={{"display":"block"}}>
            <Routes>
            <Route path={'/home'}  exact element={<HomePage/>} ></Route>
            <Route path={'/BestPage'}  exact element={<BestPage/>} ></Route>
            <Route path={'/ElectronicsPage'}  exact element={<ElectronicsPage/>} ></Route>
            <Route path={'/FashionPage'}  exact element={<FashionPage/>}></Route>
            <Route path={'/GamingPage'}  exact element={<GamingPage/>} ></Route>
            <Route path={'/HomeAppliancesPage'}  exact element={<HomeAppliancesPage/>} ></Route>
            <Route path={'/FurnituresPage'}  exact element={<FurnituresPage/>} ></Route>
            <Route path={'/GroceriesPage'}  exact element={<GroceriesPage/>} ></Route>
            </Routes>
        </div></div>
    
    )
}

export default Navbar;

您不能为组件使用模板文字字符串。

但您可以根据自己的目的使用此方法

<Routes>
{
  Object.keys(Nav_items).map((key,index) => {
    const Component = pageNav[key];
    return (
      <Route path={`/${pageNav[key]}`} exact element={<Component />} />
    )
  })
  <Route path={'/home'}  exact element={<HomePage/>} ></Route>
</Routes>

为此,您必须在 渲染 JSX 之前计算组件

Choosing the Type at runtime

<Routes>
  {Object.keys(Nav_items).map((key) => {
    const Component = pageNav[key];
    return <Route path={`/${Component}`} element={<Component />} />
  )}
  <Route path={'/home'} element={<HomePage/>} />
</Routes>

这似乎假设路由路径和要渲染的组件命名相同,这可能并不总是理想或实用。

我建议一些结构更像:

const Nav_items = [
  {
    path: ".....",
    Component: MyComponent,
  },
  ...
];

为每个条目明确指定路径和组件:

<Routes>
  {Nav_items.map(({ path, Component }) => (
    <Route key={path} path={path} element={<Component />} />
  ))}
  <Route path={'/home'} element={<HomePage/>} />
</Routes>

更新

给定:

let Nav_items = {
  "Best Sellers": ["Redmi Note 7 Pro", "Mac Pro 2","LG TV 5", "Airtel Data Card"],
  "Electronics": ["Mobiles", "Laptops", "Accessories", "Smart Devices"],
  "Fashion": ["Men's Casual wear", "Women's Casual wear", "Men's Formal wear", "Children's wear", "Accessories"],
  "Gaming": ["Gaming Laptops", "Build PCs", "Gaming Mobiles", "Controllers", "Games"],
  "Home Appliances": ["TVs", "Washing Machines", "Refrigerators", "Ovens", "Air Conditioners", "Water Purifiers"],
  "Furnitures": ["Tables and Desks", "Sofas and Chairs", "Wardrobes", "Beds and Mattresses", "Chimneys and Kitchen set"],
  "Groceries": ["Vegetables", "Masala items", "Instant foods", "Cosmetics", "Hygiene Products"]
}

None 的 Nav_items 对象键是您导入的任何 React 组件的名称:

import ElectronicsPage from '../SubPages/ElectronicsPage/ElectronicsPage';
import FashionPage from '../SubPages/FashionPage/FashionPage';
import BestPage from '../SubPages/BestPage/BestPage';
import FurnituresPage from '../SubPages/FurnituresPage/FurnituresPage';
import GamingPage from '../SubPages/GamingPage/GamingPage';
import GroceriesPage from '../SubPages/GroceriesPage/GroceriesPage';
import HomeAppliancesPage from '../SubPages/HomeAppliancesPage/HomeAppliancesPage';
import Mainpage from '../Homepage/MainPage';
import HomePage from '../Homepage/Homepage';

BUT pageNav 似乎将 page/link 映射到组件名称

const pageNav = {
  "Best Sellers": "BestPage",
  "Electronics": "ElectronicsPage",
  "Fashion": "FashionPage",
  "Gaming": "GamingPage",
  "Home Appliances": "HomeAppliancesPage",
  "Furnitures": "FurnituresPage",
  "Groceries": "GroceriesPage"
}

您正在尝试将 Nav_items 对象键映射到 pageNave 中的值,但这些值是字符串,而不是 React 组件。

{Object.keys(Nav_items).map((key) => {
  const Component = pageNav[key]; // <-- String values!!!
  return <Route path={`/${Component}`} element={<Component />} />
)}

要解决,请修复 pageNav 中的映射,以便值 导入的 React 组件。

const pageNav = {
  "Best Sellers": BestPage,
  "Electronics": ElectronicsPage,
  "Fashion": FashionPage,
  "Gaming": GamingPage,
  "Home Appliances": HomeAppliancesPage,
  "Furnitures": FurnituresPage,
  "Groceries": GroceriesPage
}

现在 const Component = pageNav[key]; 实际上应该引用一个 React 组件并且可以正常渲染,但由于它不再是字符串,因此不适用于路由 path。你仍然需要一个字符串。我建议使用 key。您可能对空格有疑问,因此您可能希望将其删除。

{Object.keys(Nav_items).map((key) => {
  const Component = pageNav[key];
  return <Route path={`/${key.replace(/\W/g, '')}`} element={<Component />} />
)}