React等待其父级调用的子方法来验证子组件中的表单

时间:2019-12-19 05:23:22

标签: reactjs

我正在尝试从其父级调用子方法以验证子组件中的表单。

进行验证时,表单values被传递到父组件this.props.formData(values)

它正在工作,但是由于异步特性,当我第一次尝试在其Parent组件中尝试console.log(this.state.form_data)时,它什么也不记录。

再次运行并使其完美,它将记录表格数据(尽管有1次迭代滞后)

请问我如何能第一次获取数据。

谢谢

子组件

class Child extends Component {
    constructor(props) {
        super(props);
        this.state = {
            values: {},
        };
    };

    componentDidMount() {
        this.props.onRef(this)
    }
    componentWillUnmount() {
        this.props.onRef(undefined)
    }

    handleSubmit() {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.props.formData(values)
                return true
            }
            else {
                this.props.formData(null)
                return false
            }
        });
    };

    render() {
        return (
            <Form onSubmit={this.handleSubmit}>
                ...
            </Form>
        );
    }
}

父母

class Parent extends Component {
    constructor(props) {
        super(props);
        this.state = {
            form_data: '',
        };

        this.getDatafromForm = this.getDatafromForm.bind(this);
    }

    getDatafromForm = (value) => {
        this.setState({ form_data: value })
    }

    beforeUpload() {
        this.child.handleSubmit();
        if (this.state.form_data !== '') {
            console.log(this.state.form_data);
        }
        else {console.log(this.state.form_data);
        }

    }

    render() {

        return (
            <Child formData={this.getDatafromForm} onRef={ref => (this.child = ref)} />
        )
    }
}

0 个答案:

没有答案