【问题标题】:ReactJS: submit the form and call the function based on the radio button selectionReactJS:提交表单并根据单选按钮选择调用函数
【发布时间】:2018-07-24 18:20:10
【问题描述】:

在我的应用中有两个功能,带有单选按钮的表单和一个提交按钮。

//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> 
  );
}

当用户单击按钮时,调用 exportJPG 或 exportPNG(基于单选组中的选定选项)的正确方法应该是什么?

提前感谢您对此提供的任何帮助!

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    exportImage内部,取ImageFormatExportSelection的值,以此为基础进行分支。

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

    注意,您在按钮上有一个 onClick 处理程序,在您的表单上有一个 onSubmit 处理程序 - 您可能希望这两件事成为或做同样的事情。如果您使用的是表单包装器,则可能有一个 submit 道具可以帮助您 - 否则,请在按钮上使用 type="submit" 并删除 onClick

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-23
      • 2012-05-05
      • 1970-01-01
      • 2017-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多