React 和 HTML Select 组件返回 String 而不是 Integer 的最佳方式

mpa*_*tan 1 javascript jsx reactjs react-jsx

我有一个 React 类(JSX),其中包含以下(这里稍微简化了)代码:

var Select = React.createClass({
  onChange: function (ev) {
     console.log(ev.target.value);
  },
  render: function() {
     var optionsHtml = this.state.options.map(function (el) {
                    console.log(this.props.getValue(el);
                    return (
                        <option key={this.props.getValue(el)}
                                value={this.props.getValue(el)}> { this.props.getLabel(el) } 
                        </option>
                    )
                });
    return <select onChange={this.onChange}>
     {optionsHtml}
    </html>
}
Run Code Online (Sandbox Code Playgroud)

在渲染函数中,console.log 在初始化 Options-HTML 并设置值时返回整数值(即 1, 2, 3),但是在 onChange-method 中的值是一个字符串(即 "1", "2 ", "3") 当实际的选择框值改变时。

解决此问题的一种方法是在 onChange 中使用该值之前检查并将其转换为 Number,但还有其他方法可以做到吗?

编辑:

选项数组可能看起来像这样

var options = [
  { id: 1, name: "Test" },
  { id: 2, name: "Test2" },
  { id: 3, name: "Test3" }
]
Run Code Online (Sandbox Code Playgroud)

然后可以使用 getValue 和 getLabel 函数调用组件,如下所示:

<Select options={options}, 
   getValue: function(v) {
      return v.id;
   },
   getLabel: function(v) {
      return v.name;
   }/>
Run Code Online (Sandbox Code Playgroud)

一旦我生成要发送到后端的 JSON,不同类型就会成为一个问题,我需要在某个时候进行转换。

Nic*_*ber 5

当您的onChange函数执行并尝试读取value选项标记的 时,重要的是要记住所有属性都将作为字符串读取。

话虽如此,请注意

onChange: function (ev) {
   console.log(ev.target.value);
   //          ^^^^^^^^^^^^^^^ always string
}
Run Code Online (Sandbox Code Playgroud)

因此,每次要处理onChange函数中的值时,都必须将该值转换为数字。像这样的事情应该可以解决问题:

onChange: function (ev) {
   var valueInt = parseInt(en.target.value, 10);
   console.log(valueInt);
}
Run Code Online (Sandbox Code Playgroud)

或者,如果该值不一定是数字,则可以尝试将其解析为数字(如果适用):

onChange: function (ev) {
   var valueInt;
   try{
       valueInt = parseInt(en.target.value, 10);
   }catch(e){ 
        // handle value not being a number if unexpected
   }
   console.log(valueInt);
}
Run Code Online (Sandbox Code Playgroud)