我想渲染一个 HTML 复选框,其选中状态由数据控制。
给出一个接收一个无状态组件item
type { label: string, checked: bool}
,
Like so:
let component = ReasonReact.statelessComponent("TodoItem");
let make = (~item, _children) => {
render: _self => {
<li> <input type_="checkbox" {/*looking for something like this*/ item.checked ? "checked" : "" /* doesn't compile */}/> {ReasonReact.string(item.label)} </li>
}
}
如何添加该属性的存在checked
to the input
标签基于item.checked == true
健康)状况?
正如 @wegry 在评论中所说,直接传递值似乎更适合您的用例,因为item.checked
已经是一个布尔值,并且checked
需要一个布尔值。
但更笼统地回答,由于 JSX 属性只是底层的可选函数参数,因此您可以使用一种简洁的语法技巧来显式传递option
到它:只需在值前面加上?
。以你的例子:
let component = ReasonReact.statelessComponent("TodoItem");
let make = (~item, _children) => {
render: _self => {
<li> <input type_="checkbox" checked=?(item.checked ? Some(true) : None) /> {ReasonReact.string(item.label)} </li>
}
}
或者,举一个您已经有选择的示例:
let link = (~url=?, label) =>
<a href=?url> {ReasonReact.string(label)} </a>
这记录在标题为显式传递可选 https://reasonml.github.io/docs/en/function#explicitly-passed-optional在 Reason 文档的 Function 页面上。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)