问题
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