簡體   English   中英

如何使用React和Rails創建表單?

[英]How to create forms with React and Rails?

使用Rails,我使用form_for標記創建表單。

Rails自動生成HTML表單,包括authenticity_token,以防止跨站點請求偽造(CSRF)。

使用React我使用JSX,因此我無法在React組件中呈現erb。

在React組件中,我手動編寫HTML。

我想在我的Rails應用程序中使用React,並且仍然具有Rails的優點。

或者 ,如果在使用React作為我的應用程序的V時無法獲得form_for的Rails優勢,我該如何編寫一個適當的表單作為React組件?

如果我首先編寫我的form_for,然后查看渲染的HTML,復制它,並粘貼到我的React組件中,這是一個好主意嗎?

例如,這里是form_for呈現的HTML:

 <form class="new_user" id="new_user" action="/users" accept-charset="UTF-8" method="post"> <input name="utf8" type="hidden" value="&#x2713;" /><input type="hidden" name="authenticity_token" value="1AXH9blzaH4qEAAWTvu6aAH84btA/9DZCpFDBhiJ0/H9uAKsPAB/rFQWY1VmWA1yNtFaigO50p6joa3X8CItBA==" /> <div class="field"> <label for="user_Имя">Имя</label><br> <input placeholder="Бил Гейтс" type="text" name="user[name]" id="user_name" /> </div> <div class="actions"> <input type="submit" name="commit" value="Открыть заявку" class="button tiny" /> </div> </form> 

您可以將authenticity_token粘貼到react組件中。

使用gem react-rails

= react_component 'Form', authenticity_token: form_authenticity_token

form_authenticity_token是rails助手。

所以你可以將它粘貼到表單中。

<form role='form' accept-charset="UTF-8" action='/action' method='post'>
  ...
  <input type='hidden' name='authenticity_token' value={this.props.authenticity_token} />
  ...
</form>

這不是最好的解決方案。 如果有人能說出更好的解決方案,我會很高興。

你可以這樣做:

$(document).ready(function(){
  $.ajaxSetup({
    headers: {
      'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
    }
  });
});

並將csrf-token放入視圖/布局中的元標記中(如果尚未存在)。

如果使用Rails呈現基本HTML並使用react-rails將React組件嵌入其中,則可以這樣寫:

var YourForm = React.createClass({
  render: function() {
    var csrfToken = $('meta[name=csrf-token]').attr('content');
    return (
      <form action='/users' method='post' accept-charset='UTF-8'>
        <input type='hidden' name='_method' value='patch' />
        <input type='hidden' name='utf8' value='✓' />
        <input type='hidden' name='authenticity_token' value={csrfToken} />
        ...
      </form>
    );
  }
});

您可以在不可見的塊內渲染表單,然后將其克隆到react組件中

/* app/assets/stylesheets/users.scss */
.invisible-form-container {
  display: none;
}
# app/views/users/edit.html.haml
.invisible-form-container
  = render 'form'
.react-container
# app/assets/javascripts/components/form.js.jsx.coffee
class @Form extends React.Component
  html_form: ->
    {__html: $('.invisible-form-container').html()}
  render: ->
    `<div dangerouslySetInnerHTML={this.html_form()} />`
# app/assets/javascripts/initializer.coffee
$ ->
  ReactDOM.render(
    `<Form />`,
    $('.react-container')[0]
  )

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM