【问题标题】:how to form submit on load in react js?如何在反应js中形成加载提交?
【发布时间】:2020-10-16 14:59:42
【问题描述】:

当页面在 ReactJS 中加载时如何提交form

<form id="redirectForm" method="post" action="https://test.cashfree.com/billpay/checkout/post/submit">
  <input type="text" name="appId" value={this.state.appId}/>
  <input type="text" name="orderId" value={this.state.orderId}/>
  <input type="text" name="orderAmount" value={this.state.orderAmount}/>
  <input type="text" name="orderCurrency" value={this.state.orderCurrency}/>
  <input type="text" name="orderNote" value={this.state.orderNote} />
  <input type="text" name="customerName" value={this.state.customerName}/>
  <input type="text" name="customerEmail" value={this.state.customerEmail} />
  <input type="text" name="customerPhone" value={this.state.customerPhone} />
  <input type="text" name="returnUrl" value={this.state.returnUrl} />
  <input type="text" name="notifyUrl" value={this.state.notifyUrl} />
  <input type="text" name="signature" value={this.state.signature}/>
  <button type="submit">Pay</button>
</form>

Javascript:

<script>document.getElementById("redirectForm").submit();</script>

【问题讨论】:

  • 您实际上可以在 componentDidMount 中为旧版本或在 useEffect 中做同样的事情(没有依赖关系)
  • @kimobrian254 分享示例代码 document.getElementById("redirectForm").submit() 就像在 react js 中一样
  • @ManjuanthVM react 运行常规 JS,因此只需执行 document.getElementById("redirectForm").submit(); 即可按预期工作。正如我在 componentDidMount 中所说的旧版本在 useEffect 中用于较新的反应版本。
  • @kimobrian254 谢谢它的工作,祝你有美好的一天

标签: javascript reactjs forms


【解决方案1】:

实际上可以为表单创建一个ref,如果组件是类组件,可以使用componentDidMount提交表单,或者如果是功能组件,可以通过useEffect提交

<form ref={item => this.form = item} id="redirectForm" method="post" action="https://test.cashfree.com/billpay/checkout/post/submit"> 
.....
</form>

在您的 React 组件中,您可以使用以下方法创建 ref:

class SampleClass extends React.Component {
   constructor() {
     this.form = null
   }

   componentDidMount() {
    this.form.submit();
   }
}

您可以使用 useRef 和 useEffect 将类似的逻辑应用于功能组件。

更多详情:https://reactjs.org/docs/refs-and-the-dom.html

【讨论】:

    猜你喜欢
    • 2023-04-02
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    • 2022-11-02
    • 2017-10-17
    • 2019-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多