Javascript ReactJS:提交表单并根据单选按钮选择调用函数
在我的应用程序中有两个功能,带有单选按钮的表单和提交按钮Javascript ReactJS:提交表单并根据单选按钮选择调用函数,javascript,reactjs,Javascript,Reactjs,在我的应用程序中有两个功能,带有单选按钮的表单和提交按钮 //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.Im
//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>
);
}
//将所选图像格式添加到状态的函数
handleImageFormatExportSelection(e){
this.setState({ImageFormatExportSelection:[e.target.value]},()=>console.log('export image as:',this.state.ImageFormatExportSelection');
}
//以JPG格式导出图像的函数
exportJPG(e){…}
//函数以PNG格式导出图像
exportPNG(e){…}
render(){
返回(
this.exportImage()}>Submit
);
}
当用户单击按钮时,调用exportJPG或exportPNG(基于单选组中选定的选项)的正确方法是什么?
提前感谢您对此的任何帮助 在
exportImage
的内部,只需获取ImageFormatExportSelection
的值,然后根据该值进行分支
if (this.state.ImageFormatExportSelection === "png") { // or whatever it is
this.exportPNG()
} else {
this.exportJPG()
}
值得注意的是,您在按钮上有一个onClick
处理程序,在表单上有一个onSubmit
处理程序-您可能希望这两件事成为或做相同的事。如果您使用的是表单包装器,则可能有一个submit
道具可以帮助您完成此操作-否则,请使用按钮上的type=“submit”
,然后单击onClick