2016-08-03 746 views
1

我有一个react-bootstrap <Checkbox >Reactjs:Jsx组件三元内联(嵌套三元组)

它看起来像这样:

<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错误。你应该如何做出反应呢?

编辑:

我忘了提及的是,复选框确实是包裹在三元

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

我同时使用三元运营商内部{ }标签得到一个JSX标记错误。

回答

2

使用checked属性的React句柄布尔值form inputs

<input type={"checkbox"} checked={true} /> 
<input type={"checkbox"} checked={false} /> 

组件应该监听onChange事件,尤其是当它是一个可控的形式输入。

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

而且,抬起头:

意识到,企图改变正常化处理的多选和单选投入,阵营代替change事件的使用click事件。除非在change处理程序中调用preventDefault,否则大多数情况下其行为与预期相同。即使checked被切换,preventDefault也会停止浏览器直观地更新输入。这可以通过取消对preventDefault的呼叫,或者将登录的开关置于setTimeout来解决。

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


编辑

在JSX,下面的语法意味着同样的事情。

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

请参阅文档中的boolean attributes section

+0

感谢您的回复,但请参阅我的编辑。 – ApathyBear

+1

@AathyBear请尝试我建议的解决方案,这就是为什么我花时间帮助你。而不是使用'checked'属性的三元组,使用布尔属性。 – AJcodez