How to submit form from a button outside that component in React?

后端 未结 6 1018
野趣味
野趣味 2020-12-31 02:07

I have a form in one of my React components, and and in the outside component that calls it I want to pass a reference to a button there, so that I can also submit that usin

6条回答
  •  青春惊慌失措
    2020-12-31 02:24

    You can achieve this by using regular HTML capabilities (HTML form Attribute), no need to use the React hacks:

    Add "id" attribute to your form: id='my-form'

    class CustomForm extends Component {
        render() {
            return (
                 
    // Form Inputs go here
    ); } }

    Then add the same Id to the "form" attribute of the target button outside of the form:

    
    

    Now, the 'Outside Button' button will be absolutely equivalent as if it is inside the form.

    Note: This is not supported by IE11.

提交回复
热议问题