【问题标题】:React Material UI RadioGroup not working with FormControlLabel returned by componentReact Material UI RadioGroup不适用于组件返回的FormControlLabel
【发布时间】:2018-12-30 18:40:33
【问题描述】:

我在将材质 UI RadioGroup 与组件返回的 FormControlLabels 结合使用时遇到问题。

目前我试试这个:

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

GenreItem的渲染函数是这样的:

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

我的问题是 FormControlLabel 无法正常工作,因为 "handleRadioSelection" 没有在任何选择上触发。

现在我发现从 Radio 元素生成的 input 元素没有 name="genreSelection" 作为属性,这意味着它不属于上面定义的 RadioGroup。

如果我将 FormControlLabelGenreItem 中直接放入 this.state.genres.map 函数中,一切正常。

是我做错了什么还是这只是材质 UI 的限制?

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    如果您查看RadioGroup 的代码,您会发现它克隆了您提供给它的子代并添加了几个属性。您需要将这些属性带到FormControlLabel。 您可以通过更改GenreItem 来呈现FormControlLabel 来实现这一点,如下所示:

    // 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"
        />
    

    添加{...labelProps}会继承RadioGroup添加的props。

    此外,如果您希望标签和值相同,则将value 显式传递给GenreItem 而不是label 很重要,因为RadioGroup 使用value 属性来帮助确定@987654334 @属性。

    这是一个工作示例:

    【讨论】:

    • 感谢您的回复。通过您建议的更改,我得到Warning: Received `true` for a non-boolean attribute `radiobutton`.。看起来标签元素无法处理我的属性。我找到的解决方法是将radiobutton="something" 添加到FormControlLabel。但这真的很脏。此外,我现在必须自己处理 Radio 元素的选中属性...
    • 谢谢!现在看起来不错。即使我必须自己在 Radio 元素上设置选中的属性。但这对我来说完全没问题。
    • 您不必在 Radio 元素上设置任何内容。我的例子不是。
    • 我意识到为什么检查不适合您,请参阅我更新的答案(您需要将值显式传递给 GenreItem)。
    • 是的,这是最后一招!我永远不会发现>_>非常感谢你:)
    猜你喜欢
    • 1970-01-01
    • 2022-10-21
    • 2019-02-22
    • 2020-09-29
    • 2021-07-27
    • 2021-09-10
    • 2019-07-31
    • 1970-01-01
    • 2016-12-26
    相关资源
    最近更新 更多