How to conditionally set HTML attributes in JSX us

2019-07-14 05:44发布

问题:

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.