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

后端 未结 6 1016
野趣味
野趣味 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:17

    Edit: Simple and correct answer: https://stackoverflow.com/a/53573760/5271656

    In React, data flows down and actions flow up. So notify child component about button click in the parent.
    This is how you can do this.

    import React, { Component } from "react";
    import ReactDOM from "react-dom";
    
    class CustomForm extends Component {
      handleOnSubmit = e => {
        e.preventDefault();
        // pass form data
        // get it from state
        const formData = {};
        this.finallySubmit(formData);
      };
    
      finallySubmit = formData => {
        alert("Form submitted!");
      };
    
      componentDidUpdate(prevProps, prevState) {
        if (this.props.submitFromOutside) {
          // pass form data
          // get it from state
          const formData = {};
          this.finallySubmit();
        }
      }
    
      render() {
        return (
          
    ); } } class App extends Component { constructor(props) { super(props); this.state = { submitFromOutside: false }; } submitCustomForm = () => { this.setState({ submitFromOutside: true }); }; componentDidMount() { console.log(this.form); } render() { return (
    ); } } const rootElement = document.getElementById("root"); ReactDOM.render(, rootElement);

    To me, this solution is hacky and not in a react way but serves your use-case.
    Find working solution here:https://codesandbox.io/s/r52xll420m

提交回复
热议问题