首页 文章

如何使用MaterialUI使用Redux-form获取Textfield输入值

提问于
浏览
1

目标:从材质UI组件获取输入值,并将它们传递给handleSubmit函数中的操作创建者 .

<Field name='email'
                  component={email =>
                   <TextField
                    fullWidth
                     autoComplete='off'
                      className={classes.textField}
                      id='email-text-field'
                      label='Email'
                      value={email} />
                    } />

                 <Field name='password'
                  component={password =>
                    <TextField
                      type='password'
                      fullWidth
                      autoComplete='off'
                      className={classes.textField}
                      id='password-text-field'
                      label='Password'
                      value={password} />
                    } />

这是它连接到Redux的方式:

@reduxForm({form:'loginForm',fields:['email','password']})

我在chrome dev工具控制台中收到的警告是:Failed prop type:提供给TextField的prop value 无效 . 警告:失败的道具类型:提供给输入的无效道具 value

此外,我的登录表单中的电子邮件字段显示[对象,对象}我的猜测是,这是因为道具正在从

关于我哪里出错的任何想法?

1 回答

  • 1

    当您想为Redux-Form使用自定义字段时,Redux-form允许您访问两个道具,如 onChange 等, but also other meta-data (就像是否触摸过表格一样) . 这些不同种类的 props are grouped depending on type .

    有趣的是,与普通输入元素相关的所有属性(如 onChangevaluetype )都在 props.input 中分组 . 因此,您调用 password 的参数实际上是发送到组件的整个 props 对象 . 它看起来像这样 {input:{ value: 'someValue', onChange: somFunction.. etc. etc}, meta: { touched: false, etc. etc.}} .

    这意味着如果你想像现在这样使用 TextField ,你需要做类似的事情:

    <Field name='email'
        component={({input}) =>
          <TextField
             value={input.value}
             onChange={input.onChange}
             fullWidth
             autoComplete='off'
             className={classes.textField}
             id='email-text-field'
             label='Email'
            />
         } />
    

    这可能会变得非常混乱,特别是如果你想使用 meta 道具,所以将自定义组件逻辑分解为自己的函数通常是值得的,就像它们在文档中的示例中所做的那样:https://redux-form.com/7.0.4/examples/material-ui/

    您可能也有兴趣知道对于 material-ui 组件,实际上已经存在library that has done most of that manual work for you: redux-form-material-ui .

相关问题