简体   繁体   中英

React Creating Menu items by a function

I have a menu with list items like below

   <MenuItem
      //className={this.classes.menuItem}
      onClick={this.handleClose}
    >
      <NavLink
        to={Constants.pagesURL+page}
        //className={this.classes.menuItemAnchor}
      >
        {Constants.pagesName+page}
      </NavLink>
    </MenuItem>

I want to wrap this with menuItem(page) function so within the page, all I need to do is {this.menuItem('Home')} and {this.menuItem('Page1')} to get menu items populated, easy and clean..

The struggle is I want the name I send when calling the function to be added to the Constant name.. For example, if I do {this.menuItem('Home')} then {Constants.pagesName+page} needs to be actually {Constants.pagesNameHome} ..

I tried as above with adding + in front of page I send in, not working.. I tried {Constants.pagesName[page]} not working, I tried to create let pageName = 'pagesName'+page; then doing {Constants.pagesName} that didn't work either. How can I get this work?

As it is {Constants.pagesURL+page} I get 'undefinedHome' and 'undefinedPage1'...

你试过了吗:

const menuItem = (page) => `${Constants.pagesURL}${page}`;

Okay this was rather easy as I expected.. Playing around, I figured this is the way to go..

{Constants['pagesURL'+page]}

Works as a charm!

Full code:

   menuItem(page) {
      return(
        <MenuItem
          //className={this.classes.menuItem}
          onClick={this.handleClose}
        >
          <NavLink
            to={Constants['pagesURL'+page]}
            //className={this.classes.menuItemAnchor}
          >
            {Constants['pagesName'+page]}
          </NavLink>
        </MenuItem>
      )
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM