【问题标题】:React JSX selectively pass attribute to componentReact JSX 选择性地将属性传递给组件
【发布时间】:2021-01-05 01:14:20
【问题描述】:

此代码有效,但我不禁认为有更好的方法。我无法将扩展设置为 false,因为当我这样做时组件会中断(就像他们在 Set JSX attribute based on another JSX attribute react 中所做的那样)

另外,我需要添加更多的条件分支,这意味着代码重复

if (itemProps.Expanded == true) {
  return (
    <Accordion expanded={true}>
    ...
    </Accordion >
  )
}
else {
  return (
    <Accordion>
    ...
    </ Accordion>
  )
}

有什么建议吗?

【问题讨论】:

  • &lt;Accordion expanded={itemProps.Expanded == true}&gt;
  • 出现什么错误?

标签: javascript reactjs jsx


【解决方案1】:

您可以动态创建 props 对象并使用 ...(spread) 传递 props

const props = itemProps.Expanded == true ? { expanded: true } : {};
return <Accordion {...props}>...</Accordion>;

【讨论】:

    【解决方案2】:

    抱歉,伙计们尝试了这个,它奏效了。感谢您的宝贵时间

    let expanded = undefined;
    if (itemProps.Expanded) {
      expanded = true;
    }
    
    return (
        <Accordion expanded={expanded}>
        ...
        </Accordion >
    )
    ```
    

    【讨论】:

    • 这样做expanded={itemProps.Expanded ? true : undefined}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    • 2016-08-31
    • 2021-01-03
    • 2020-02-28
    相关资源
    最近更新 更多