简体   繁体   中英

Conditionally setting html attributes in React.js

I'm having a surprisingly hard time setting a default option for a radio button component in React.

Here is my RadioToggle component:

/** @jsx React.DOM */
var RadioToggle = React.createClass({
  render: function () {
    var self = this;
    return (
      <div className="RadioToggle">
        {this.props.radioset.radios.map(function(radio, i){
          return (
            <label className="__option" key={i}>
              <h3 className="__header">{radio.label}</h3>

              {radio.checked ?
                <input className="__input"
                     type="radio"
                     name={self.props.radioset.name}
                     value={radio.value}
                     defaultChecked />

              : <input className="__input"
                     type="radio"
                     name={self.props.radioset.name}
                     value={radio.value} />
              }

              <span className="__label"></span>
            </label>
            )
          })
        }
      </div>
    );
  }
});

module.exports = RadioToggle;

And here is how I'm creating the component:

<RadioToggle radioset={
  {
    name: "permission_level",
    radios: [
    {
      label: "Parent",
      value: 1,
      checked: false
    },
    {
      label: "Child",
      value: 0,
      checked: true
    }
  ]}
}/>

The above code works, but we don't like generating almost identical code depending on the radio.checked option.

The way the component is set up, I pass it a name and an array of radios to create, and for each object in the radios array use that data to create a radio button.

In other cases I've been able to conditionally set attributes by putting ternary statements as the value, like below, but that doesn't work here.

The problem with defaultChecked={radio.checked ? "checked" : ""} defaultChecked={radio.checked ? "checked" : ""} is that even with the output becoming checked="checked" on one radio button and checked on the other, it makes both radio buttons checked by default, resulting in the last one actually being checked.

Again, the component above works, but I'm hoping someone with some more experience with React will have a cleaner way of doing it rather than generating almost identical elements except for that attribute.

checked/defaultChecked take booleans, not strings.

<input className="__input"
     type="radio"
     name={self.props.radioset.name}
     value={radio.value}
     defaultChecked={radio.checked} />

jsbin demo

Side note: avoid defaultChecked/defaultValue and use checked/value with onChange instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM