form onSubmit vs onClick

class AddOption extends React.Component {
  handleAddOption(e) {
    e.preventDefault();
    const option = e.target.elements.option.value.trim();
    if (option) {
      alert("handleAddOption");
    }
  }
  render() {
    return (
      <div>
        <form onSubmit={this.handleAddOption}>
          <input type="text" name="option" />
          <button>AddOption</button>
        </form>
      </div>
    );
  }
}

Form onSubmit is a more correct approach, for the simple reason that a form can also be submitted with the ENTER key, and not just by clicking the submit button.

The name attribute specifies the name of an element.

The name attribute is used to reference elements in a JavaScript, or to reference form data after a form is submitted.

Note: Only form elements with a name attribute will have their values passed when submitting a form.

上一篇:Python+selenium 启用带插件的chrome浏览器


下一篇:【完美解决】 ModuleNotFoundError: No module named ‘pip‘[ using the `--user` option]