Dynamically generate radio buttons

为君一笑 提交于 2020-01-15 06:36:22

问题


I have a redux form where I included some radio buttons:

     <label htmlFor="passType">Pass type</label>
        {passType.touched && passType.error && <span className="error">{passType.error}</span>}
        <br />
        <input
          type="radio"
          {...passType}
          id="passType"
          value="0"
          checked={passType.value === '0'}
        /> VIP<br />
        <input
          {...passType}
          type="radio"
          id="passType"
          value="1"
          checked={passType.value === '1'}
        /> Regular<br />

All well and good, but now the pass types must be dynamically generated from state:

PassTypes":[{"Id":1,"Name":"VIP"},{"Id":2,"Name":"Normal"}]

This doesn't work:

const renderPassTypes = passTypes => passTypes.map((passType, i) => 
(
  <input
    type="radio"
    {...passType}
    id="passType"
    value={passType.Id}
    checked={passType.Id === ?!?!?} 
  /> {passType.Value}<br />
)

How should I go about coding a group of radio buttons from an object?

I also have a validator that needs to continue to function as well:

const sendInviteValidator = createValidator({
  passType: required,
});

回答1:


What you tried seems good.

render() {
  // Extract the fields from Redux Form
  const {fields: {passType}} = this.props

  // Read the options.
  // According to what you showed, it is structured as:
  //
  // [
  //   {"Id":1,"Name":"VIP"},
  //   {"Id":2,"Name":"Normal"},
  // ]
  const {passTypes} = this.props
  return (
    <div>
      <div className="label">Pass type</div>
      <div className="controls">
      {passTypes.map(option =>
        <label>
          <input
            type="radio"
            {...passType}
            value={option.Id}
            checked={passType.value === option.Id}
          />
          {option.Name}
        </label>
      )}
      </div>
    </div>
  )
}

The above render method is iterating over passTypes to construct the radio inputs.



来源:https://stackoverflow.com/questions/36900129/dynamically-generate-radio-buttons

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