将 dangerouslySetInnerHTML 字符串表单中的 formRef 映射到组件内的 formRef

Mapping the formRef inside a dangerouslySetInnerHTML string form in to the formRef inside the component

我遇到这个问题,我需要提交我通过 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();