首页 > 解决方案 > 在 React js 中渲染组件内部的函数

问题描述

我的目标是在 react js 中创建一个面包屑组件。我在我的应用程序中使用了 Ant Design,但其中一部分存在一些问题。

在 Ant Design 的文档中,我找到了创建动态面包屑的解决方案,但找不到如何应用代码。

使用 Ant design 我构建了下一个应用程序:

    import React from "react";
    import {Link, BrowserRouter, Route} from "react-router-dom";
    import {Breadcrumb} from 'antd';

    //from here starts the code from Ant Design Documentation
    const routes = [
        {
            path: 'index',
            breadcrumbName: 'home',
        },
        {
            path: 'first',
            breadcrumbName: 'first',
            children: [
                {
                    path: '/general',
                    breadcrumbName: 'General',
                },
                {
                    path: '/layout',
                    breadcrumbName: 'Layout',
                },
                {
                    path: '/navigation',
                    breadcrumbName: 'Navigation',
                },
            ],
        },
        {
            path: 'second',
            breadcrumbName: 'second',
        },
    ];

    function itemRender(route, params, routes, paths) {
        const last = routes.indexOf(route) === routes.length - 1;
        return last ? (
            <span>{route.breadcrumbName}</span>
        ) : (
            <Link to={paths.join('/')}>{route.breadcrumbName}</Link>
        );
    }
return <Breadcrumb itemRender={itemRender} routes={routes} />;
    //here is the end of the code from Ant Design

    function App() {
        return (
            <div>
                <p>here i want to render my breadcrumb</p>
            </div>
        );
    }

    export default App;

此外,return 语句位于函数之外,因此我得到错误。

如何使用此实现创建面包屑,以及如何itemRender在我的组件中呈现函数,以及我应该从哪里获得这些参数itemRender(route, params, routes, paths)

标签: javascriptreactjs

解决方案


您需要Breadcrum在 App body 中使用组件

function App() {
  return (
      <div>
        <Breadcrumb itemRender={itemRender} routes={routes} />
      </div>
  );
}

推荐阅读