簡體   English   中英

react-form-validator沒有注冊子組件?

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

我正在使用'react-form-validator-core'軟件包,並嘗試創建一個實現'mui-downshift'的自定義表單驗證器, 'mui-downshift'是PayPal降級的Material UI實現。 這個問題主要是關於'react-form-validator-core'包本身的。 問題在於表單本身未注冊我創建的驗證器組件。 這是我的自定義組件和表單本身的完整代碼。 我已經用盡了調試技巧,但是我注意到的是this.context格式有問題...

驗證器組件:

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;

使用它的組件:

    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 >
        )
   };
};

之所以會出現此問題,是因為您從ValidatorComponent重寫了默認的componentWillMountcomponentWillReceiveProps方法。 因此,要解決這種情況,您應該執行以下操作

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM