在 Redux 表单中渲染 material-ui-next 复选框

IT技术 reactjs redux material-ui redux-form
2021-05-24 01:39:58

我在尝试material-ui-nextredux-form. 我正在关注官方示例并尝试将其调整为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 行<Checkbox />是在上述renderCheckbox()方法中定义组件

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