首页 > 解决方案 > 如何将材质 ui 组件包装为字段的 redux 表单组件?

问题描述

我想了解如何将material ui组件包装到redux-formField 组件中?

<FormControl variant='outlined' className={classes.textField}>
            <InputLabel
              ref={ref => {
                this.InputLabelRef = ref
              }}
              htmlFor='outlined-county-simple'
            >
              {this.state.countryName}
            </InputLabel>
            <Select
              value={this.state.country}
              onChange={this.handleChangeCountry}
              input={
                <OutlinedInput
                  labelWidth={this.state.labelWidth}
                  name='country'
                />
              }
            >
              {isData(country) ? country.map((entity, index) => {
                return (
                  <MenuItem value={entity.code} key={`county-${index}`}>{entity.country}</MenuItem>)
              }) : null}
            </Select>
          </FormControl>

结果我想从这个组件获取数据到 redux-form 存储,这种情况是用户将选择的。我可以通过使用 redux 的 change 函数来实现,但我认为这不是正确的工作方式。我有示例如何将 TextField 组件包装到 redux 表单组件中

import mapProps from 'recompose/mapProps'
import TextField from '@material-ui/core/TextField'

export default mapProps(({
  input: {name, onChange, value},
  meta: {touched, error},
  helperText,
  ...restProps
}) => ({
  error: !!(touched && error),
  fullWidth: true,
  helperText: (touched && error) ? error : helperText,
  margin: 'normal',
  onChange: event => onChange(event.target.value),
  value,
  ...restProps
}))(TextField)

标签: reactjsmaterial-ui

解决方案


这应该有效。我们可以将组件传递给 Field,如代码片段所示,在我的例子中是 renderSelectField。

 <Field
          name="favoriteColor"
          component={renderSelectField}
          label="Favorite Color"
        >

推荐阅读