gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:54:46 25 4
gpt4 key购买 nike

我有一个 react-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 token 错误三元运算符中的标签。

最佳答案

React 句柄 bool 值 form inputs使用 checked 属性。

<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在文档中。

关于javascript - Reactjs:组件的 Jsx 三元内联(嵌套三元),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38750742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com