首页 文章

React / Redux - 如何从组件内访问表单输入错误

提问于
浏览
0

我有一个redux表单,当输入未验证时显示错误,这一切都很好,花花公子,但我正试图在用户访问时通过提交按钮创建一个全局的“请填写必填字段”提交,作为一种方式让用户知道“哦,嘿,我需要向上滚动并找到一些未填写的内容” .

我的connect函数如下所示:

export default reduxForm({
    form: 'requestForm',
    validate,
})(connect(mapStateToProps, mapDispatchToProps)(RequestForm));

其中 validate 是一个单独的js文件,如下所示:

function validate(formProps) {
    const errors = {};

            if (!formProps.get('account_name')) {
                errors.account_name = 'Required';
            }
            if (!formProps.get('street')) {
                errors.street = 'Required';
            }
            if (!formProps.get('city')) {
                errors.city = 'Required';
            }
            if (!formProps.get('state')) {
                errors.state = 'Required';
            }
            if (!formProps.get('zip')) {
                errors.zip = 'Required';
            }
            if (!formProps.get('contact_name')) {
                errors.contact_name = 'Required';
            }
            if (!formProps.get('contact_phone')) {
                errors.contact_phone = 'Required';
            }

    return errors;
}

export default validate;

在我的组件中,有没有办法可以访问 errors 属性并确定提交时的错误总数?

1 回答

  • 0

    因此,当使用Redux Form时,您可以通过 this.props 访问许多道具,所以我所做的就是添加一段HTML,如下所示:

    {!this.props.valid && !this.props.pristine &&
        <p style={{color:"#f44336", fontSize: "12px", marginTop: "10px"}}>*Please fill in all required fields</p>
    }
    

    我正在做的就是检查 this.propspristinevalid 属性并且效果很好!

相关问题