Rails Country_Select Gem In ReactJs

Rails Country_Select Gem In ReactJs

本文关键字:In ReactJs Gem Select Country Rails      更新时间:2023-09-26

今天早上我尽量不做一些愚蠢的事情,但我发现自己喜欢使用HTML5 data-*属性。我安装了country_select rails gem,它在html.erb中运行良好,形式为:

<%= f.country_select :location, { priority_countries: ["GB", "US"], selected: "GB" } %>

我把它引入Reactjs的愚蠢方法是:

html.erb:

<div id="foo" data-countries="<%= f.country_select :location, { priority_countries: ["GB", "US"], selected: "GB" } %>"></div>

对于以上内容,我通常会为方法执行此操作。

js.jsx:

getInitialState: function() {
  return {
    location: this.props.data.location
  }
},
geo: function(event) {
  this.setState({location: event.target.value});
},
render: function(){
  var bar = document.getElementById('foo');  
  return (
      <div>
        <select
           value={this.state.location}
           onChange={this.geo}
         >
           <option value="" selected disabled>Please select</option>
           <option value="{bar.dataset.countries}">{bar.dataset.countries}</option>
         </select>
      </div>
    )
 }

在我看来,所有国家都是因为html.erb中的data-countries而吐出来的。同样在渲染的下拉菜单中,我看到"请选择"和<select name=

我知道我所做的是100%不正确的。如果可能的话,用这块宝石有正确的方法吗?

我找到了!基本上,你需要从国家宝石获得名称:

在您的用户模型中:

def country
  country = ISO3166::Country
  c = country.all
  c.map do |a| a.name end
end

现在在适当的控制器中:

def method_name
 c = User.new
 # Calling the method from user.rb
 @country = c.country
end

由于我使用的是react rails,在我看来:

<%= react_component('NewProject', { country: @country }) %>

js.jsx:

render: function(){
  var country = (c) => (<option key={c} value={c}>{c}</option>) 
  return (
      <div>
        <select
           value={this.state.location}
           onChange={this.geo}
         >
           <option value="" selected disabled>Please select</option>
           {this.props.country.map(country)}
         </select>
      </div>
    )

现在我得到了我的下拉菜单。希望这对其他人有用!