在 JSX 中添加布尔值

Adding boolean values in JSX

我有一个场景,我想在我的 JSX 中添加一个简单的布尔值。它只是一个标志,表示某物是否处于活动状态。

<NavItem href="#/gosomewhere" active >

我不确定如何在 JSX 中传递 'active' 标志。

我认为这会很好:

const active= location.pathname.match(/^\/gosomewhere/) ? "active" : "";

return(

                <NavItem eventKey={1} href="#/gosomewhere" {active} >
                    Go Somewhere
                </NavItem>
)

但是我得到这个错误:

Module build failed: SyntaxError: Unexpected token, expected ...

在这种情况下我是否需要以某种方式使用展开运算符?

您可以像其他道具一样传递布尔值,只需使用 active={true|false}:

const active = location.pathname.match(/^\/gosomewhere/);
return(
   <NavItem eventKey={1} href="#/gosomewhere" active={active} >
     Go Somewhere
   </NavItem>
)

回答"is active=true equivalent to just 'active' ?"

是的,active={true} 等同于 activeW3C recommandation

建议只标记 active

我将此作为答案发布,因为我没有足够的声誉来发表评论。