【问题标题】:Why must I use the spread operator in this JSX element?为什么我必须在这个 JSX 元素中使用扩展运算符?
【发布时间】:2020-08-09 02:04:20
【问题描述】:

我有一个功能组件,它返回一个锚元素,该元素可以具有hrefrole 属性,具体取决于传递给它的props

function Item(props) {
    return (
        <a {...props.toSubMenu && {role: 'button'}} {...props.href && {href: props.href}}>
            {props.children}
        </a>
    );
}

在创建这个组件时,我首先尝试在不使用扩展运算符的情况下传递 props,如下所示: &lt;a {props.toSubMenu &amp;&amp; {role: 'button'}}&gt;,但这给了我错误:

解析错误:意外的令牌,应为“...”

所以目前,我的组件按我想要的方式工作,但我无法弄清楚为什么我必须使用扩展运算符。在我的代码的其他部分(如第 4 行)我不需要它。我在this questionthis onereact documentation 中读到过它,但我仍然不确定。

【问题讨论】:

  • 不,你不能;这是一个非常错误的传播用法;

标签: reactjs jsx


【解决方案1】:

在 JSX 中,{} 不像许多模板语言那样输出字符串,您需要将其视为左手是属性的赋值, 现在根据设置道具设置值只需遵循相同的逻辑: 解释为什么错误显示预期的“...”。如果 {} 不位于分配的右侧,则预计您希望分散多个属性, 所以,试试这个

function Item(props) {
    return (
        <a role={props.toSubMenu ? 'button' : undefined} href={props.href}>
            {props.children}
        </a>
    );
}

【讨论】:

    【解决方案2】:
    • 我从你的代码中提取这个作为例子
    function Item(props) {
        return (
            <a {...props.toSubMenu && {role: 'button'}} >
                {props.children}
            </a>
        );
    }
    
    • 假设props.toSubMenu 不是null
    • 转换为纯html后:(这根本不起作用!)
    function Item(props) {
        return (
            <a {role: 'button'} >
                {props.children}
            </a>
        );
    }
    
    • 如果你像这样使用扩展运算符
    function Item(props) {
        return (
            <a {...props.toSubMenu && ...{role: 'button'}} >
                {props.children}
            </a>
        );
    }
    
    • 它将对象{role: 'button'} 展开为:
    function Item(props) {
        return (
            <a role="button" >
                {props.children}
            </a>
        );
    }
    
    • 需要注意的一点:在
    {...props.toSubMenu && {role: 'button'}}
    

    最外面的{}不是object的符号,它是code snippetjsx文件中运行的标志。

    结论

    • 您不必使用展开操作,这也有效
    function Item(props) {
        return (
            <a role={props.toSubMenu && 'button'} >
                {props.children}
            </a>
        );
    }
    
    • 但既然role 已经在props 中定义了,为什么不把它散开呢?

    【讨论】:

      【解决方案3】:

      如果toSubMenu 是真的,我假设你想给&lt;a/&gt; 角色button?你只想转发href? 在那种情况下,以下方法会起作用吗?

      function Item(props) {
          return (
              <a role={props.toSubMenu ? 'button' : undefined} href={props.href}>
                  {props.children}
              </a>
          );
      }
      

      【讨论】:

      • 虽然这行得通(就像我在我的问题中发布的代码一样),但这并不是我问题的真正答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-02
      • 1970-01-01
      • 1970-01-01
      • 2016-04-28
      相关资源
      最近更新 更多