【问题标题】:React input select to display corresponding components & select string value to number value反应输入选择以显示相应的组件并将字符串值选择为数字值
【发布时间】:2018-08-29 15:19:11
【问题描述】:

我正在填充一个选择列表并从同一个 json 中绘制相应的信息组件。 Select 设置了 .map 和所有正确的值..(我认为)。 onChange 被分配给 countryChange ,它接受一个事件值和 setStates 来传递触发器。

我不明白的是, 1. e.target.value 是字符串而不是数字, 2.当一个state赋值为0时,e.target.value和state返回不同​​的值...

this.state={
 selectedCountry:0
}



      countryChange( e ) {
            const list = e.target.value;
            const countrylist = this.props.countries.find(c => c.id === list)
              this.setState({
                    selectedCountry: countrylist
                   // selectedCountry: parseInt(e.target.value, 10) 
                });
            }
        render() {
                    return(
                      <select id="exampleSelect" onChange={this.countryChange.bind(this)}>
                      <option value="d">Select Country</option>
                     {this.props.countries.map((item) => ( <option key={item.id} value={item.id}> { item.name } </option> ))}</select>

之后,我将 selectedCountry 作为 props 发送给其他组件以呈现信息。我一直在寻找其他类似的问题和答案,并且走了这么远,但似乎无法按照我想要的方式完全执行它。

【问题讨论】:

    标签: reactjs select


    【解决方案1】:

    对于 HTML &lt;option&gt; 元素,value 属性被浏览器解释为字符串。 (HTML specifications 将其描述为 DOMString 类型。)看起来您已经知道如果您希望它是数字,则需要将其转换为数字,但我认为您做得有点晚了使您的比较工作。怎么样

    const list = parseInt(e.target.value);
    

    改为countryChange 的第一行?

    或者,您可以只进行所有比较字符串比较。您可能希望您的 .id 属性是字符串,并且您希望您的初始 setState 成为 {selectedCountry: "0"}

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-21
    • 2020-01-29
    • 1970-01-01
    • 1970-01-01
    • 2015-02-18
    相关资源
    最近更新 更多