How to conditionally set HTML attributes in JSX using reason-react?

此生再无相见时 提交于 2020-01-04 06:50:14

问题


I want to render an HTML checkbox whose checked state is controlled by data.

Give a stateless component that receives an 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>
  }
}

How do I add the presence of the attribute checked to the input tag based on the item.checked == true condition?


回答1:


As @wegry said in a comment, it seems to fit your use case better to just pass the value directly since item.checked already is a boolean, and checked takes a boolean.

But to answer more generally, since JSX attributes are just optional function arguments under the hood, you can use a neat syntactic trick to be able to explicitly pass an option to it: Just precede the value with ?. With your example:

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>
  }
}

Or, to give an example where you already have an option:

let link = (~url=?, label) => 
  <a href=?url> {ReasonReact.string(label)} </a>

This is documented in the section titled Explicitly Passed Optional on the Function page in the Reason docs.



来源:https://stackoverflow.com/questions/52844663/how-to-conditionally-set-html-attributes-in-jsx-using-reason-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!