【问题标题】:Rendering material-ui-next Checkbox inside a Redux Form在 Redux 表单中渲染 material-ui-next 复选框
【发布时间】:2018-09-26 10:47:23
【问题描述】:

我在尝试在redux-form 中呈现一个简单的material-ui-next 复选框时遇到了一些麻烦。我正在关注official example 并尝试将其调整为等效的material-ui-next,因为该示例使用的是旧版本的material-ui。这是我最终使用的代码:

const renderCheckbox = ({ input, label }) => (
  <FormGroup row>
    <FormControlLabel
      control={
        <Checkbox
          checked={input.value ? true : false}
          onChange={input.onChange}
          value="checkedA"
        />
      }
      label="Secondary"
    />
  </FormGroup>
);

这就是我在redux-form 中定义复选框的方式:

...
<Field name="activated" component={renderCheckbox} label="Activated" />
...

但是,当我保存代码时,React 抱怨以下错误:

index.js:2178 警告:React.createElement:类型无效 -- 期望一个字符串(对于内置组件)或一个类/函数(对于 复合组件)但得到:未定义。您可能忘记导出 你的组件来自它定义的文件,或者你可能混合了 设置默认和命名导入。

在 myForm.js:108 检查您的代码。

代码的第 108 行是在上述renderCheckbox() 方法中定义的&lt;Checkbox /&gt; 组件。

【问题讨论】:

  • 您是否将内容正确导入到组件文件中?我运行你上面的代码没有问题。根据错误行号,您可能错误地导入了 Checkbox 组件。

标签: reactjs redux material-ui redux-form


【解决方案1】:

当我终于找到解决这个问题的方法时,我也被这个问题困扰了很长一段时间。 它永远不会适用于返回复选框的功能组件。 我制作了一个单独的类组件并将其包装在 Redux Field 组件中,它运行良好。我真的不明白为什么它不适用于功能组件,因为它在他们的官方示例中显示。

我已经编写了适合我的代码。希望对你有帮助:)

class CheckBoxInput extends React.Component {

  onCheckBoxSelectChange = (input) => 
  {
    input.onChange();
    this.props.onSelectChange();
  }

  render() {
    const { label, input,} = this.props;
    let name = input.name;

    return (
      <div>
        <InputLabel htmlFor={label} style={{paddingTop: '15px'}}> {label} </InputLabel>
         <FormControl {...input} >
          <Checkbox
            name = {name}
            label = {label}
            color= "primary"
            checked={input.value ? true : false}
            onChange={() => this.onCheckBoxSelectChange(input)}
          />          
        </FormControl>
      </div>

    )
  }
}

const CheckBox = (props) => <Field component={CheckBoxInput} {...props} />;
export default CheckBox;

并使用此复选框组件:

 <CheckBox  name="isCurrent" label="Current" onSelectChange = {this.toggleCurrentEmployerSelection} />

【讨论】:

    猜你喜欢
    • 2019-04-12
    • 2020-09-29
    • 2019-03-27
    • 1970-01-01
    • 2017-11-18
    • 2017-03-27
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    相关资源
    最近更新 更多