简体   繁体   中英

React get input value on form submit and display it

I have the following script at: http://codepen.io/AlexanderWeb00/pen/gLVbjL?editors=0010

class Wrapper extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: ''
    };
  }
  handleFirstName(e) {
    this.setState({name: e.target.value});
  }
  render(){
    return (
      <section>
        <h2>welcome</h2>
        <TShirt name={this.state.name} />
        <FormButton action={this.handleFirstName.bind(this)} />
      </section>
    )
  }
};

class TShirt extends React.Component {
  render(){
    return (
      <section>
        <div>
          <p>Name: {this.props.name}</p>
        </div>
      </section>
    )
  }
};
class Extention extends React.Component {
  render(){
    return (
      <section>
        <div>
          <p>badaboom</p>
        </div>
      </section>
    )
  }
};
var FormButton = React.createClass({ 
    getInitialState: function() {
        return {'submitted': false};
    },

    handleSubmit: function(e) {
        e.preventDefault();
        this.setState({'submitted': true });
    },
    render: function() {
        if (this.state.submitted) {
            return <Extention/>;
        }
        else {
            return (
                <form role="form" onSubmit={this.handleSubmit}>
                    <input type="text" />
                    <input type="submit" value="submit" />
                </form> 
            );
        }
    }
}); 

ReactDOM.render(<Wrapper />, document.getElementById('app'));

I want to display the value collected from the input

<input type="text" />

here:

<p>Name: {this.props.name}</p>, inside the TShirt component.

At the moment is only displaying a new component after the form is submitted. The Tshirt component will be updated with more content as I build the application.

You can use refs to get the value of the tshirt input field and then call the callback function passed to FormButton component in the action prop.

var FormButton = React.createClass({ 
getInitialState: function() {
    return {'submitted': false};
},

handleSubmit: function(e) {
    e.preventDefault();
    var tshirt = this.refs.tshirt.value;
    this.setState({submitted: true }, function() {
      this.props.action(tshirt);
    });
},
render: function() {
    if (this.state.submitted) {
        return <Extention/>;
    }
    else {
        return (
            <form role="form" onSubmit={this.handleSubmit}>
                <input type="text" ref="tshirt" />
                <input type="submit" value="submit" />
            </form> 
        );
    }
}
});

Then modify the handleFirstName method to this:

handleFirstName(tshirt) {
    this.setState({name: tshirt});
}

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