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

后端 未结 6 992
野趣味
野趣味 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 pass the onSubmit click handler as a props as follows:

    import React, { Component } from "react";
    import ReactDOM from "react-dom";
    
    class CustomForm extends Component {
    
      render() {
        return (
          
    ); } } function App() { handleSubmit = () => { alert('Form submitted!') } return (
    ); } const rootElement = document.getElementById("root"); ReactDOM.render(, rootElement);

    Passing function as a props to handle form submit makes the CustomForm element more reusable since the business logic for the submit is not part of CustomForm component.

提交回复
热议问题