简体   繁体   English

Rails Country_在ReactJs中选择宝石

[英]Rails Country_Select Gem In ReactJs

I'm trying not to do something stupid this morning but I'm finding myself love to use the HTML5 data-* attribute. 我今天早上不想做一些愚蠢的事情,但是我发现自己喜欢使用HTML5 data-*属性。 I have installed country_select rails gem and it works great in html.erb , within a form: 我已经安装了country_select rails gem,并且在html.erb中以一种形式很好地工作:

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

My stupid way of pulling this into Reactjs would be: 我将其引入Reactjs的愚蠢方法是:

html.erb: html.erb:

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

For the above, I normally do this for methods. 对于以上内容,我通常对方法执行此操作。

js.jsx: 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>
    )
 }

In my views, all the countries are spitted out caused by the data-countries in the html.erb . 在我看来,所有国家/地区都是由html.erbdata-countries地区html.erb Also in the rendered dropdown menu, I see the "Please Select" and <select name= 同样在呈现的下拉菜单中,我看到了“请选择”和<select name=

I know what I'm doing is 100% incorrect. 我知道我在做什么是100%错误的。 Is there a correct way on doing this, if possible with this gem? 如果可能的话,有没有正确的方法来做到这一点?

I have found it! 我找到了! Basically you'll need to get the name from the country gem : 基本上,您需要从country gem获得名称

In your User Model: 在您的用户模型中:

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

Now somewhere in the appropriate controller: 现在在适当的控制器中的某个位置:

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

Since I'm using react-rails , in my views: 由于我在使用react-rails ,因此在我看来:

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

js.jsx: 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>
    )

Now I got my drop down. 现在我得到了支持。 Hope this is useful to others! 希望这对其他人有用!

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

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