简体   繁体   中英

React GET form data on submit

I'm new to React and I've been facing a problem since few hours now. Even if I found some topics on Stackoverflow or Google that seems equivalent to my issue, I'm unable to solve it...

I'm using react-select to create a simple form. For now, I have only one multi-select input. I am able to use it as expected but when I press "Submit" I want to retrieve the values selected. I tried with refs , with onChange without success. onChange is never fired, that might be an other issue as well.

var MultiSelect = React.createClass({
    onLabelClick: function (data, event) {
        console.log(data, event);
    },

    render: function() {
      var ops = []

      this.props.categories.forEach(function(category) {
      ops.push({ label: category.name, value: category.id });
    });

        return (
            <div>
                <Select
                    name = {this.props.name}
                    delimiter=" "
                    multi={true}
                    allowCreate={true}
                    placeholder = {this.props.label}
                    options={ops} />
            </div>
        );
    }
});


var ProductForm = React.createClass({
  submit: function () {
    console.log("Categories: " + this.state.categories);
  },

  onCategoryChange: function(e) {
    console.log("CATEGORY CHANGED !!!!!!")
    this.setState({categories: e.target.value});
    },

  render: function () {
    return (
      <form onSubmit={this.submit}>
        <MultiSelect label="Choose a Category" name="categories" categories={this.props.categories} onChange={this.onCategoryChange}/>
        <button type="submit">Submit</button>
      </form>
    );
  }
});

PS : data categories comes from a Rails controller.

I believe your internal Select component should receive onChange from the props provided to MultiSelect , assuming your intention is to listen to changes on the Select component.

Try something like this inside your MultiSelect 's render() method:

return (
    <div>
        <Select
            name = {this.props.name}
            delimiter=" "
            multi={true}
            allowCreate={true}
            placeholder = {this.props.label}
            options={ops} 
            onChange={this.props.onChange} />
    </div>
);

Side note, I don't think e.target.value is going to work inside onCategoryChange , since react-select doesn't send standard events.

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