简体   繁体   中英

ReactJS: submit the form and call the function based on the radio button selection

In my app there are two functions, form with radio buttons and a submit button.

//function that adds the selected image format to the state

handleImageFormatExportSelection(e) {
    this.setState({ ImageFormatExportSelection: [e.target.value] }, () => console.log('export image as:', this.state.ImageFormatExportSelection));
}

//function that exports image in JPG format
exportJPG(e) {...}

//function that exports image in PNG format
exportPNG(e) {...}

render() {
  return (

    <form onSubmit={this.handleFormSubmit}>
      <div className="exportAs">
        <CheckboxOrRadioGroup
          title={'Export image as:'}
          setName={'exports'}
          controlFunc={this.handleImageFormatExportSelection}
          type={'radio'}
          options={this.state.exportOptions}
          selectedOptions={this.state.ImageFormatExportSelection} />
      </div>

      <button onClick={() => this.exportImage()}>Submit</button>
    </form> 
  );
}

What should be the right way to call either exportJPG or exportPNG (based on the selected option in radio group) when user clicks the button?

Thank you in advance for any help with this!

inside of exportImage , just take the value of ImageFormatExportSelection , branch based on that.

if (this.state.ImageFormatExportSelection === "png") { // or whatever it is
  this.exportPNG()
} else {
  this.exportJPG()
}

of note , you have an onClick handler on the button and an onSubmit handler on your form - you probably want these two things to be or do the same thing. If you're using a form wrapper, there's probably a submit prop that helps with this - otherwise, use type="submit" on the button and drop the onClick

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