如何使用单独的函数动态组成React组件?

问题描述 投票:0回答:1

我有一个函数,可以沿着一棵简单的树走,并在每个步骤调用函数以打印菜单:

renderMenuFx(menu, renderFx) {
    renderFx.startMenu()
    for (const entry of menu) {
        renderFx.startEntry()
        renderFx.renderEntry(entry.path.join(""), entry.title)
        if (entry.menuEntries) {
            this.renderMenuFx(entry.menuEntries, renderFx)
        }
        renderFx.endEntry()
    }
    renderFx.endMenu()
}

并且在登录控制台时有效:

this.renderMenuFx(tree, {
    startMenu() { console.log('<ul>') },
    endMenu() { console.log('</ul>') },
    startEntry() { console.log('<li>') },
    endEntry() { console.log('</li>') },
    renderEntry(path, title) { console.log(`<a href="${path}">${title}</a>`) },
})

但是当我尝试在React中渲染它时就没有了:

<div>

{
    f.renderMenu(this.tree, {
        startMenu() { return ( <ul> ) },
        endMenu() { return ( </ul> ) },
        startEntry() { return ( <li> ) },
        endEntry() { return ( </li> ) },
        renderEntry(path, title) { return ( <a href={path}>{title}</a> ) },
    })
}

</div>

实际上,问题在于它无法编译,给出:

./src/components/Menu/MenuDyn.js
Syntax error: Unexpected token (141:37)

  139 |                     f.renderMenu(this.tree, {
  140 |                         startMenu() { return ( <ul> ) },
> 141 |                         endMenu() { return ( </ul> ) },
      |                                     ^

我显然做错了:处理这种情况的正确方法是什么?

javascript reactjs react-component
1个回答
0
投票

开始实验的简单示例:

在某些<Menu menu={someData} />类组件中

render () {
  return (
    <ul>
      {this.props.menu.map((entry) => (
        <Entry key={entry.id} data={entry}></Entry>
      ))}
    </ul>
  )
}

渲染(功能)子组件:

const Entry = props => (
  <li>
    {props.data.title}
    {props.data.menuEntries && (
      <Menu menu={props.data.menuEntries} />
    )}
  </li>
)
© www.soinside.com 2019 - 2024. All rights reserved.