简体   繁体   English

React-将ref传递给父对象

[英]React - passing ref to parent

I am trying to think the react way but I can't find a solution on how to invoke the .submit() method of the form component. 我正在尝试思考反应方式,但是找不到如何调用表单组件的.submit()方法的解决方案。

I have a material-ui Dialog where I have to pass the buttons via actions property. 我有一个材质用户界面对话框,我必须在其中通过actions属性传递按钮。 From this action component, I would like to invoke the .submit() method of the Form component, which is a child of the dialog. 从这个动作组件中,我想调用Form组件的.submit()方法,该方法是对话框的子级。

Do I have to pass the formRef up to the Dialog to pass it then to the Actions, and how would I do that? 我是否必须将formRef传递给Dialog才能将其传递给Actions,我该怎么做? Or is there any React way I am missing out on? 还是我错过了任何React方法

class FormDialog extends React.Component {
    render() {
        return (
            <Dialog actions={<Actions />} >
                <Form />
            </Dialog>
        )
    }
}

const Actions = (props) => {
    return (
        <FlatButton
            label="Submit"
            onTouchTap={() => formRef.submit()}
        />
    )
} 

const Form = () => {
    let formRef;
    return (
        <AutoForm 
            ref={ref => formRef = ref}
            onSubmit={doc => db.save(doc)} 
            >
        </AutoForm>
    )
} 

Any buttons inside a form that submit the form should be type="submit" , and clicking on any of them will trigger the <form /> 's onSubmit handler. 提交表单的表单中的任何按钮都应为type="submit" ,单击它们中的任何按钮都会触发<form />onSubmit处理程序。 There's no need to pass around a reference. 无需传递参考。

There's a few React-way notes here: 这里有一些React-way注释:

  • If you have to pass things "up" and then back "down" a component tree, you're probably not approaching the problem correctly. 如果您必须先“向上”传递某个组件树,然后再向下“向下”传递组件树,则可能无法正确解决该问题。
  • Components should never call methods on other components. 组件绝不能在其他组件上调用方法。
  • Unless you really know when they're needed, refs to DOM elements should only be referenced inside the component owning the ref. 除非您真的知道何时需要它们,否则仅应在拥有该引用的组件内部引用对DOM元素的引用。

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

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