React Material UI RadioGroup not working with FormControlLabel returned by component

╄→尐↘猪︶ㄣ 提交于 2020-01-06 05:50:09

问题


I have an issue working with the material UI RadioGroup in combination with FormControlLabels returned by a component.

Currently I try this:

<FormControl component="fieldset">
  <RadioGroup
    row
    name="genreSelection"
    className="genre-wrapper"
    value={this.state.selection}
    onChange={this.handleRadioSelection}
  >
  {
    this.state.genres.map(genre => (
      <GenreItem key={genre} label={genre} radioButton/>
    ))
  }
  </RadioGroup>
</FormControl>

And the render function of GenreItem looks like this:

if (this.props.radioButton) {
  return (
    <FormControlLabel
      value={this.props.label}
      label={this.props.label}
      control={
        <Radio/>
      }
      className="genre-item"
    />
  );
}
// Another return here

My problem is that the FormControlLabel isn't working correctly as "handleRadioSelection" isn't triggered on any selection.

By now I found out that the input element generated from the Radio element doesn't have name="genreSelection" as attribute which means it doesn't belong to the RadioGroup defined above.

If I put the FormControlLabel out of GenreItem and directly into the this.state.genres.map function everything is working just fine.

Am I doing something wrong or is this just a limitation of material UI?


回答1:


If you look at the code of RadioGroup you'll find that it clones the children that you provide to it and adds several properties. You need to carry those properties down into FormControlLabel. You can accomplish that by changing GenreItem to render the FormControlLabel as follows:

// assign radioButton separately so it isn't part of labelProps
const { radioButton, ...labelProps } = this.props;
if (radioButton) {
    <FormControlLabel {...labelProps }
      label={this.props.value}
      control={
        <Radio/>
      }
      className="genre-item"
    />

Adding {...labelProps} will carry forward the props added by RadioGroup.

Also if you want the label and value to be the same, it is important to pass value explicitly to GenreItem rather than label since RadioGroup uses the value prop to help determine the checked property.

Here's a working example:



来源:https://stackoverflow.com/questions/53980379/react-material-ui-radiogroup-not-working-with-formcontrollabel-returned-by-compo

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