如何使用 reason-react 在 JSX 中有条件地设置 HTML 属性?
How to conditionally set HTML attributes in JSX using reason-react?
我想呈现一个 HTML 复选框,其选中状态由数据控制。
给出一个接收 item
类型的无状态组件 { label: string, checked: bool}
,
像这样:
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>
}
}
如何根据 item.checked == true
条件将属性 checked
添加到 input
标签?
正如@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>
这在 Reason 文档的函数页面上标题为 Explicitly Passed Optional 的部分中有记录。
我想呈现一个 HTML 复选框,其选中状态由数据控制。
给出一个接收 item
类型的无状态组件 { label: string, checked: bool}
,
像这样:
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>
}
}
如何根据 item.checked == true
条件将属性 checked
添加到 input
标签?
正如@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>
这在 Reason 文档的函数页面上标题为 Explicitly Passed Optional 的部分中有记录。