简体   繁体   English

react-form-validator没有注册子组件?

[英]react-form-validator not registering children components?

I am using 'react-form-validator-core' package and trying to create a custom form validator that implements 'mui-downshift' , a Material UI implementation of PayPal's downshift. 我正在使用'react-form-validator-core'软件包,并尝试创建一个实现'mui-downshift'的自定义表单验证器, 'mui-downshift'是PayPal降级的Material UI实现。 This question is mostly about 'react-form-validator-core' package itself. 这个问题主要是关于'react-form-validator-core'包本身的。 The problem is that the form itself does not register the validator component I've created. 问题在于表单本身未注册我创建的验证器组件。 Here is my full code of the custom component and the form itself. 这是我的自定义组件和表单本身的完整代码。 I've exhausted my debugging skills, but what I noticed is that there's something wrong with the this.context in the form... 我已经用尽了调试技巧,但是我注意到的是this.context格式有问题...

Validator component: 验证器组件:

import React from 'react';
import PropTypes from 'prop-types';
import MuiDownshift from 'mui-downshift';
import { ValidatorComponent } from 'react-form-validator-core';


class AutocompleteValidator extends ValidatorComponent {
    constructor(props) {
        debugger;
        super(props);

        this.originalItems = props.items.map(({key, name}) => ({ text: name, value: key }));

        this.handleStateChange = this.handleStateChange.bind(this);
        this.errorText = this.errorText.bind(this);
    }

    componentWillMount() {
        if (!this.filteredItems) {
            this.setState({filteredItems: this.originalItems});
        }

        if (!!this.props.value) {
            const selectedItem = this.originalItems.filter(
                item => item.value.toLowerCase().includes(this.props.value.toLowerCase())
            )[0];
            this.setState({ selectedItem })
        } else {
            this.setState({ selectedItem: null})
        }
    }

    componentWillReceiveProps(nextProps) {
        // If no filteredItems in sate, get the whole list:
        if (!nextProps.value) {
            this.setState({ isValid: false })
        }

    }

    handleStateChange(changes) {
        // If searching
        if (changes.hasOwnProperty('inputValue')) {
            const filteredItems = this.originalItems.filter(
                item => item.text.toLowerCase().includes(changes.inputValue.toLowerCase())
            );
            this.setState({ filteredItems })
        }

        // If something is selected
        if (changes.hasOwnProperty('selectedItem')) {
            !!changes.selectedItem ? this.setState({isValid: true}) : this.setState({isValid: false})
            // If we get undefined, change to '' as a fallback to default state
            changes.selectedItem = changes.selectedItem ? changes.selectedItem : '';
            this.props.onStateChange(changes);
        }
    }

    errorText() {
        const { isValid } = this.state;

        if (isValid) {
            return null;
        }

        return (
            <div style={{ color: 'red' }}>
                {this.getErrorMessage()}
            </div>
        );
    }

    render() {
        return (
            <div>
                <MuiDownshift
                    {...this.props}
                    items={this.state.filteredItems}
                    onStateChange={this.handleStateChange}
                    ref={(r) => { this.input = r; }}
                    defaultSelectedItem={this.state.selectedItem}
                />
                {this.errorText()}
            </div>
        );
    }

}
AutocompleteValidator.childContextTypes = {
  form: PropTypes.object
};

export default AutocompleteValidator;

A component where it's used: 使用它的组件:

    render() {
        return (
            <ValidatorForm
                ref='form'
                onSubmit={() => {
                    this.context.router.history.push(this.props.config.urls['step5']);
                }}
                onError={errors => console.log(errors)}
            >
                <Row>
                    <Col md={12}>
                        <AutocompleteValidator
                            validators={['required']}
                            errorMessages={['Cette information doit être renseignée']}
                            isRequired={true}
                            name='bankId'
                            items={this.props.config.list.bank}
                            onStateChange={(changes) => {
                                this.props.loansUpdate('bankId', changes.selectedItem.value);
                            }}
                            value={!!this.props.loans.bankId ? this.props.loans.bankId : false}
                        />
                    </Col>
                </Row>
                <Row>
                    <Col md={12} style={{ marginTop: '15px' }}>
                        <Checkbox
                            label={<Translate value='step4.insuranceProvidedByBank' />}
                            labelStyle={{ 'top': '0px' }}
                            name='insuranceProvidedByBank'
                            value={this.props.loans.insuranceProvidedByBank}
                            checked={this.props.loans.insuranceProvidedByBank}
                            onCheck={(event, value) => {
                                this.props.loansUpdate('insuranceProvidedByBank', value);
                            }}
                        />
                    </Col>
                </Row>
                <Row>
                    <Col sm={6} md={5}>
                        <Button
                            fullWidth
                            style={{ marginTop: '50px', marginBottom: '20px' }}
                            type='submit'
                            icon={<i className='fa fa-angle-right' style={{ marginLeft: '10px', display: 'inline-block' }} />}
                        ><Translate value='iContinue' /></Button>
                    </Col>
                </Row>
            </ValidatorForm >
        )
   };
};

you get this problem because you override default componentWillMount and componentWillReceiveProps methods from ValidatorComponent . 之所以会出现此问题,是因为您从ValidatorComponent重写了默认的componentWillMountcomponentWillReceiveProps方法。 So, to solve this case you should do something like this 因此,要解决这种情况,您应该执行以下操作

    componentWillMount() {
        // should call parent method before
        super.componentWillMount();
        // your code
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM