react.js - show a message on and after form submission

前端 未结 1 1334
小蘑菇
小蘑菇 2021-02-05 11:43

On submitting the form, I want to show \'Please wait ..\' and on successful submission the data returned from server. Using jQuery , it is easy to do. But there should be a Reac

1条回答
  •  执念已碎
    2021-02-05 12:24

    This is definitely something React can handle, no direct DOM manipulation is needed. You're almost there, just need to reorganize a little. Here's one way to approach this (with comments around important changes):

    var FormComp = React.createClass({
    
      // To get rid of those input refs I'm moving those values
      // and the form message into the state
      getInitialState: function() {
        return {
          name: '',
          email: '',
          message: ''
        };
      },
    
      handleSubmit: function(e) {
    
        e.preventDefault();
    
        var userName = this.state.name.trim();
        var userEmail = this.state.email.trim();
    
        if(!userName || !userEmail) return;
    
        this.setState({
          name: '',
          email: '',
          message: 'Please wait...'
        });
    
        // I'm adding a callback to the form submit handler, so you can
        // keep all the state changes in the component.
        this.props.onFormSubmit({
          userName: userName, 
          userEmail: userEmail, 
          url: "/api/submit"
        }, function(data) {
          this.setState({ message: data });
        });
      },
    
      changeName: function(e) {
        this.setState({
          name: e.target.value
        });
      },
    
      changeEmail: function(e) {
        this.setState({
          email: e.target.value
        });
      },
    
      render: function() {
        // the message and the input values are all component state now
        return (
          
    { this.state.message }
    Name:
    Email:
    ); } }); var RC = React.createClass({ onFormSubmit: function(data, callback){ $.ajax({ url: this.props.url, dataType: 'json', type: 'POST', data: data, success: callback, error: function(xhr, status, err) { console.error(this.props.url, status, err.toString()); }.bind(this) }); }, render: function() { return } }); React.render( , document.getElementById('content') );

    0 讨论(0)
提交回复
热议问题