问题描述
我遇到了这个问题,我需要提交通过api服务获取的htmlString提供的表单。
import React from 'react';
import { Button } from 'antd';
class SampleClass extends React.Component {
constructor() {
super();
this.formRef = React.createRef();
}
render() {
// An html form like this is obtained through an api and rendered
const stringHTML =
'<form\n' +
' ref={this.formRef}\n' + // I want this reference of this form to be mapped to the this.formRef
' id="ext-merchant"\n' + // that I've created in the constructor
' action="http://localhost:3011/add"\n' +
' method="post"\n' +
' acceptCharset="UTF-8"\n' +
' encType="application/x-www-form-urlencoded"\n' +
'>\n' +
' <input\n' +
' type="text"\n' +
' id="msisdn"\n' +
' name="msisdn"\n' +
' value="3454"\n' +
' />\n' +
' <input\n' +
' type="hidden"\n' +
' id="amount"\n' +
' name="amount"\n' +
' value="3454"\n' +
' />\n' +
' <input type="submit" value="Submit" style="display: none;" />\n' +
'</form>';
return (
<>
<div dangerouslySetInnerHTML={{ __html: stringHTML }} />
<Button
onClick={() => {
this.formRef.current.submit();
}}
>
Example Button
</Button>
</>
);
}
}
export default SampleClass;
一些有关此问题或其他替代方法的说明可能会有所帮助。如果有更好的方法来提交收到的表格,请提出建议。
解决方法
我能够通过使用表单ID来访问并提交来完成表单提交。
document.getElementById('ext-merchant-frm').submit();