在react + redux中,从子组件访问父项属性的最佳方法是什么?

时间:2017-07-10 07:53:35

标签: javascript reactjs redux

我遇到这个问题,我在Dialog中打开一个表单(来自material-ui)。该对话框具有自己的状态({open:true})和一些处理该状态的属性(handleOpen,handleClose,将setState设置为true或false的func)。我迷路的地方是,在成功提交表单后,我想关闭父对话框。基本上,我想在父级上调用handleClose fn。

export class ContactFormDialog extends React.Component<{}, {}> {
state = {
    open: false
};
handleOpen = () => {
    this.setState({ open: true });
};
handleClose = () => {
    this.setState({ open: false });
};
render() {
    let style = {
        margin: 12,
    };
    const actions = [
        <RaisedButton
            label={resources.general.cancelLabel}
            primary={false}
            onTouchTap={this.handleClose}
        />
    ];
    return (
        <div>
            <RaisedButton
                onTouchTap={this.handleOpen}
                label={resources.contact.askForInfo}
                primary={true}
                style={style}
            />
            <Dialog
                actions={actions}
                modal={true}
                open={this.state.open}
                autoScrollBodyContent={true}
                onRequestClose={this.handleClose}
                title={resources.contact.contactUs}
                ref="contactFormDialog"
            >
                <div className="text-center">
                    <ContactForm />
                </div>
            </Dialog>
        </div>
    );
  }
} 

联系表单如下所示 class ContactForm扩展了React.Component {

onSubmit = (values) => {
    // print the form values to the console
    this.props.submitRequest(values);
    //this is what i tried but fails to compile because this.refs.contactFD is a Element/ReactInstance and they do not have a 'handleClose' property/method.
    if (this.refs.contactFormDialog) {
        this.refs.contactFormDialog.handleClose();

    }

};

public render() {
    return (
        <ContactFormView onSubmit={this.onSubmit} />
    );
}

}

处理这类问题会有什么好处? (从孩子内部访问父属性)

0 个答案:

没有答案