【问题标题】:Optional attribute set with React JSX [duplicate]使用 React JSX 设置的可选属性 [重复]
【发布时间】:2016-01-02 06:01:53
【问题描述】:

我即将使用 React 制作下一个页面,但我找不到如何将可配置属性集放入组件中,例如:

<ProgressBar active now={current} max={total}/>

我想在 ProgressBar 中添加 active 属性,前提是 current == total

我该怎么做?

有没有一种简单的方法可以在 activestripped 两个选项之间进行切换?像这样的:

<ProgressBar {current==total ? stripped : active} now={current} max={total}/>

除了创建一个属性对象并传播它{...props}

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    如果组件正确处理false 值,只需始终添加道具:

    let stripped = this.state.current === this.state.total;
    
     <ReactBootstrap.ProgressBar
       stripped={stripped}
       active={!stripped}
       now={this.state.current}
       max={this.state.total}
     ?>
    

    如果您绝对必须传递其中一个,您可以创建一个对象并将其传播到元素中:

    let props = {
      [this.state.current === this.state.total ? 'stripped' : 'active']: true,
      now: this.state.current,
      max: this.state.total,
    };
    
    <ReactBootstrap.ProgressBar {...props} />
    

    【讨论】:

    • 嗯。我不知道 active=false 与不存在的属性具有相同的含义。谢谢。感谢{...props}
    • 好吧,我假设该组件执行if (this.props.active) { ... } 之类的操作,因此无论是未设置还是设置为false 都是一样的。
    • 有些人不喜欢不需要的附加属性……为什么要强制显示属性。我正在进入 Jest + Snapshots,这可笑地驱使我在这样的线程中寻找答案。
    • 很好的例子!对于您只想要该属性的props 解决方案,可以使用 if,例如let props = { ... }; if (needsProp) props['theProp'] = true; ...
    • 不鼓励使用语法{...props}。在内置 html 属性的情况下最好使用 defaultChecked 和类似的 react-analogues,并在其他情况下拒绝使用它们。见github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/…
    猜你喜欢
    • 2020-08-23
    • 2018-01-10
    • 1970-01-01
    • 2016-12-31
    • 2012-03-13
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    • 2018-07-17
    相关资源
    最近更新 更多