问题
I have this array Object in State called formRating
formRating:Array[22]
0:
{…}
condId: "C2.1(a)"
rate: "N/A"
1:
{…}
condId:"C2.2(b)"
rate:"3"
2:
{…}
3:
{…}
I also have a few RadioGroups in the render letting the user manipulate the state object above.
<Grid item xs={7} style={{marginTop:32}}> Condition 1</Grid> <Grid item ><RadioGroup name="C2.1(a)" defaultValue={this.getDefaultValue('C2.1(a)')} onChange={this.changeButton("C2.1(a)")} style={{display: 'flex', flexDirection: 'row'}}>
What would the getDefaultValue method be to change the rate of an element matching with the given condId with the defaultValue={this.getDefaultValue("C2.1(a)")}?
回答1:
It will make sense to define the defaultValue
of these RadioGroups
by using a .map()
to iterate over the list of formRatings
. Then you can pass in the rate seamlessly instead of passing a hard-coded string to a function.
Try something like:
createRadioGroups = () => {
const { formRating } = this.state;
return formRating.map(item => {
return (
<div>
<label>{item.condId}</label>
<Grid item>
<RadioGroup
defaultValue={item.rate}
value={item.rate}
name={item.condId}
onChange={() => this.changeButton(item.condId)}
/>
</Grid>
</div>
);
});
};
Then in your render you can use createRadioGroups()
render() {
return (
<div>
<Grid item xs={7} style={{ marginTop: 32 }}>
Condition 1
</Grid>
{this.createRadioGroups()}
</div>
);
}
回答2:
With @ChristopherNgo inspiration, following worked.
In the render;
<Grid item xs={12} style={{marginTop:20}}>{this.createRadioGroups(values.formRating)}</Grid>
and createRadioGroups method as follows;
createRadioGroups = (ratingState)=>{
return(ratingState.map(
item =>
<Grid container>
<Grid item xs={2} style={{marginTop:20, marginRight:0}}>{item.condId} </Grid>
<Grid item xs={6} style={{marginTop:20}}>{item.condition} </Grid>
<Grid item xs={4} style={{marginTop:10}}>
<RadioGroup defaultValue={item.rate} name={item.condId} onChange={this.changeButton(item.condId)} style={{display: 'flex', flexDirection: 'row'}}>
<FormControlLabel value="1" control={<Radio color="primary" />} label='' labelPlacement="top"/>
<FormControlLabel value="2" control={<Radio color="primary" />}label='' labelPlacement="top"/>
<FormControlLabel value="3" control={<Radio color="primary" />}label='' labelPlacement="top"/>
<FormControlLabel value="N/A" control={<Radio color="primary" />}label='' labelPlacement="top"/>
</RadioGroup>
</Grid>
</Grid>
))
} ;
来源:https://stackoverflow.com/questions/57322899/how-to-set-defaultvalue-of-a-radiogroup-from-a-nested-array-object-in-react-stat