简体   繁体   中英

How to render a option of select element - reactjs

I wrote this function to make a tree options.

makeTreeOption(tree) {
    let ouput = `<optgroup label="${tree.title}">`;
    if (tree['children']) {
      tree.children.forEach(children => {
        if (children['children']) {
          ouput += this.makeTreeOption(children);
        } else {
          ouput += `<option>${children.title}</option>`;
        }
      });
    }
    ouput += `</optgroup>`;
    return ouput;
  }

but when I want to render it:

  <select>
       {this.makeTreeOption(data)}
  </select>

it returns this:

在此处输入图片说明

Rather than building a string you need the makeTreeOption method to return JSX. Something like:

function makeTreeOption(tree) {
    return <optgroup /*...optgroup props */>{
        tree.children.map(
            child => child.children
                ? makeTreeOption(child)
                : <option /* ...option props */>{ child.title }</option>
        )
    }</optgroup>
}

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