简体   繁体   English

ReactJS:如何传递字符串以用作函数名?

[英]ReactJS: How can I pass a string to use as a function name?

I'm building a menu with React.我正在用 React 构建菜单。 How can I pass a string to a component to use it as a function name?如何将字符串传递给组件以将其用作函数名称?

What's working:什么工作:

<Link to={ROOM({ roomId })}>home</Link>

I'm refactoring the components now.我现在正在重构组件。 I have a component MobileMenu with the Link defined as:我有一个组件 MobileMenu,其链接定义为:

  <MobileMenuLink service={'ROOM'} />

In a second component I've defined the MobileMenuLink as:在第二个组件中,我将MobileMenuLink定义为:

const MobileMenuLink = ({ style, className, roomId, service }) => {
  return (
    <Base style={style} className={className}>
      <MenuLink>
        <Link to={service({ roomId })}>home</Link>
      </MenuLink>
    </Base>
  )
}

How is this possible?这怎么可能?

Don't pass a string, pass the ROOM function to MobileMenuLink :不要传递字符串,将ROOM函数传递给MobileMenuLink

<MobileMenuLink service={ROOM} />

And call service as you do now, because it's a function:像现在一样调用service ,因为它是一个函数:

<Link to={service({ roomId })}>home</Link>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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