【问题标题】:Adding boolean values in JSX在 JSX 中添加布尔值
【发布时间】:2017-09-05 18:11:52
【问题描述】:

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

<NavItem href="#/gosomewhere" active >

我不确定如何在 JSX 中传递“活动”标志。

我认为这会很好:

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

return(

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

但是我得到了这个错误:

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

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

【问题讨论】:

    标签: reactjs jsx react-bootstrap


    【解决方案1】:

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

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

    【讨论】:

    • is active=true 等同于 'active' ?
    • @OliverWatkins 是的,它只是 jsx 中的快捷方式
    【解决方案2】:

    回答“is active=true 等同于 'active' 吗?”

    是的,active={true} 等同于 activeW3C recommandation 建议只标记active

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

    【讨论】:

    • 虽然在html标签中推荐使用,但在jsx中一般不推荐使用。我的意思是这取决于你需要做什么
    猜你喜欢
    • 2018-01-02
    • 2020-10-21
    • 2021-08-18
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    • 1970-01-01
    • 2021-04-08
    相关资源
    最近更新 更多