简体   繁体   English

将危险的SetInnerHTML 字符串表单内的formRef 映射到组件内的formRef

[英]Mapping the formRef inside a dangerouslySetInnerHTML string form in to the formRef inside the component

I'm having this issue where I need to submit the form provided by the htmlString from I obtain via an api service.我遇到了这个问题,我需要提交通过 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;

Some light regarding this issue or some other alternatives would be helpful.关于这个问题的一些看法或其他一些替代方案会有所帮助。 If there is a better approach regarding submitting the received form, please suggest it.如果有关于提交收到的表格的更好方法,请提出建议。

我能够通过使用表单 id 访问它并提交它来简单地完成表单提交。

 document.getElementById('ext-merchant-frm').submit();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM