简体   繁体   中英

Try to get form data after submit in a React child component but empty screen

i have a problem with a child component that is a component form. I'd like to pass the form data to my parent component and then do an Ajax call.

Here is my parent component

import React, { Component } from 'react';
import { render } from 'react-dom';
import CustomerForm from './customerForm';
import styles from './scss/application.scss';

class App extends React.Component {
    constructor() {
            super();
            this._handleSubmit = this._handleSubmit.bind(this);
    }

    _handleSubmit(customer) {

        alert(customer);
        //AJAX
    }
    render() {
        return (

         <CustomerForm
            handleSubmit={this._handleSubmit}
            />
          </section>
        );
      }
}

render(
  <App />,
  document.getElementById('root')
);

Then here is the child component form CustomerForm i include :

import React, { Component } from 'react';

class CustomerForm extends Component {

    constructor(props) {
        super(props);

    }

    _onSubmit(e) {

        e.preventDefault();

        var name = this._name.value.trim();

        if (!name) {
          return;
        }

        this.props.handleSubmit({name: name, identifier: identifier, cost: cost});
    }

    render() {
    return (
             <form onSubmit={this._handleSubmit}>
                    Name <br/> <input id="name" type="text" name="name" 
        value={this.state.name}
        ref={(input) => this._name = input}/><br/>

                    <input type="submit" value="Create"/>
                 </form>

   );
  }
}
export default CustomerForm

In fact my screen is empty i do not see any error messages in my web browser web inspector, the problem comes from the child component. When i remove in my parent component everything's ok.

Any idea? Thx Laurent

You have a mistake in your form submission, change <form onSubmit={this._handleSubmit}> to <form onSubmit={this._onSubmit}> .

return (
     <form onSubmit={this._onSubmit}>
       Name <br/> 
       <input id="name" type="text" name="name" 
         value={this.state.name}
         ref={(input) => this._name = input}/><br/>
       <input type="submit" value="Create"/>
      </form>
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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