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

Best way for a React and HTML Select-component to return String instead of Integer

本文关键字:Integer 最佳 方式 HTML Select-component 返回 String React      更新时间:2023-09-26

我有一个React-class(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>
}

在渲染函数中,控制台.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" }
]

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

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

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

onChange函数执行并尝试读取选项标记的value时,请务必记住,所有属性都将作为字符串读取。

话虽如此,请注意

onChange: function (ev) {
   console.log(ev.target.value);
   //          ^^^^^^^^^^^^^^^ always string
}

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

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

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

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);
}

我会将渲染方法和事件侦听器更改为:

onChange(event) {
  const el = this.state.options[event.target.value];
  const value = this.props.getValue(el);
},
render() {
  const options = this.state.options.map((el, idx) => (
    <option key={this.props.getValue(el)} value={idx}>{ this.props.getLabel(e) }</option>
  ));
  return (
    <select onChange={this.onChange}>
      { options }
    </select>
  )
}

这样做,你没有得到实际的价值。您正在告诉"从预定义对象中选取索引 N 处的对象并获取其值。