Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
102 views
in Technique[技术] by (71.8m points)

javascript - Issues with dynamic React element creation

Disclaimer... this might turn into more of a specific js question (relating to dynamically accessing object properties using variables) ...

I am attempting to create a dynamically rendered menu where a menu schema is passed in (testinputs) and that menu is rendered complete with routing.

There are two parts to this:

  1. rendering the menu itself

  2. rending the routes

This question is about rendering the routes.

import DataGrid from "./DataGrid.js"
import AddItem from "./AddItem.js"

const AllMenuItems = {
  "DataGrid":DataGrid
  "AddItem":AddItem,
}

const testinput = {

  data: [
    {
      name: "DataGrid",
      url: "/datagrid",
    },
    {
      name: "Transact",
      children: [
        {
          name: "AddItem",
          url: "/additem",
        },
      ],
    },
  ],
};

I have a function expression that utilizes jsx to return a specific dynamic route...

Rendering works when I hard code the component prop like so, referencing the imported React component directly...

<Route path={url} component={AddItem}/>

But when I attempt to do things dynamically (see below) the routing doesn't work.

const routeBuilder = (children) => {
    return children.map((subOption) => {
      if (!subOption.children) {
        var name = subOption.name;
        var url = subOption[url];
        var MyComponent = AllMenuItems[name];    
        return (
          <Route path={url} component={MyComponent}/>
        );
      }
      routeBuilder(subOption.children);
    })
  }

What am I overlooking here? Thanks in advance.

question from:https://stackoverflow.com/questions/65661812/issues-with-dynamic-react-element-creation

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One issue is recursive routeBuilder return values are not used.

Some thing like

const routeBuilder = (children) => {
    return children.map((subOption) => {
      if (!subOption.children) {
        var name = subOption.name;
        var url = subOption[url];
        var MyComponent = AllMenuItems[name];    
        return (
          <Route path={url} component={MyComponent}/>
        );
      } else {
         return routeBuilder(subOption.children);
        }
    })
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...