Reactjs:组件的 Jsx 三元内联(嵌套三元)

Reactjs: Jsx ternary inline of a component (nested ternaries)

我有反应-bootstrap <Checkbox >.

看起来像这样:

<Checkbox inline onClick={this.handleInclude}> Include </Checkbox>

在某些情况下,我希望复选框被选中。如果要检查 api 建议执行以下操作:

<Checkbox checked inline onClick={this.handleInclude}> Include </Checkbox>

所以现在我只想在某些状态下使用 checked 关键字。所以我尝试使用三元语句:

<Checkbox 
  {this.state.chkbox === true ? "checked" : "" } 
  inline 
  onClick={this.handleInclude}> 
     Include
 </Checkbox>

但这会引发 Unexpected token 错误。你应该如何用 React 做到这一点?

编辑:

我忘了提到复选框确实是用三元包裹的

{this.state.currentView == "timeline" ?
         <Checkbox 
      {this.state.chkbox === true ? "checked" : "" } 
      inline 
      onClick={this.handleInclude}> 
         Include
     </Checkbox>
: "" 
}

我在三元运算符中使用内部 { } 标记时收到 JSX 令牌错误。

React 使用 checked 属性.

处理布尔值 form inputs
<input type={"checkbox"} checked={true} />
<input type={"checkbox"} checked={false} />

该组件应该监听 onChange 事件,尤其是当它是受控表单输入时。

<input type={"checkbox"} checked={this.state.checked} onChange={this.onChange} />

此外,请注意:

Be aware that, in an attempt to normalize change handling for checkbox and radio inputs, React uses a click event in place of a change event. For the most part this behaves as expected, except when calling preventDefault in a change handler. preventDefault stops the browser from visually updating the input, even if checked gets toggled. This can be worked around either by removing the call to preventDefault, or putting the toggle of checked in a setTimeout.

总而言之,不要在 this.onChange(event) 组件方法中调用 event.preventDefault()


编辑

在 JSX 中,以下语法意思相同。

<input checked />
<input checked={true} />

请参阅文档中的 boolean attributes section