【问题标题】:How to pass Value from a <select> in javascript如何在 javascript 中从 <select> 传递值
【发布时间】:2021-10-30 19:12:51
【问题描述】:

我试图在onChange 函数中传递&lt;select&gt; 的选定值。 我试过这个 SO Question,但 thisthis.value 不起作用。我知道这个问题有点老了......

setShippingMethod(obj) {
    console.log('Shipping method ' + JSON.stringify(obj));
    this.state.defaultMethod = obj.value;
    this.props.setShippingMethod(obj.value);
}

render() {
    const shippingMethods = this.state.shippingMethods;
    const defaultMethod = this.state.defaultMethod;        

    return (
        <aside id="checkout" className="block col-1">
            <h1>Shipping</h1>
            <div className="row">
                <select id="comboMethod" onChange={setShippingMethod(this)} value={!!defaultMethod ? null : defaultMethod.trim()}>
                    {shippingMethods.map(method => { return <option key={method.shipmthd.trim()} value={method.shipmthd.trim()}>{method.shipmthd.trim()}</option>} )}
                </select>
            </div>
        </aside>
    );
}

我的行console.log('Shipping method ' + JSON.stringify(obj)) 生成错误“未捕获的类型错误:循环对象值”,消息似乎是this 仍然指的是整个(在我的情况下)modal。有没有更新的方法来做到这一点?任何帮助将不胜感激。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    当在 react 中使用事件监听器时,你会得到一个事件对象。您可以使用 e.target.value 访问输入到元素中的值。

    setShippingMethod(e) {
        console.log('Shipping method ' + JSON.stringify(e.target.value));
        //...rest of the code
    }
    
    render() {
        const shippingMethods = this.state.shippingMethods;
        const defaultMethod = this.state.defaultMethod;        
    
        return (
            <aside id="checkout" className="block col-1">
                <h1>Shipping</h1>
                <div className="row">
                    <select id="comboMethod" onChange={setShippingMethod} value={!!defaultMethod ? null : defaultMethod.trim()}>
                        {shippingMethods.map(method => { return <option key={method.shipmthd.trim()} value={method.shipmthd.trim()}>{method.shipmthd.trim()}</option>} )}
                    </select>
                </div>
            </aside>
        );
    }
    

    【讨论】:

      【解决方案2】:

      当你在课堂上时,这总是对课堂的引用。 如果你想传递选定的选项值,你需要类似

      onChange={(e) => {setShippingMethod(e.target.value)}}
      

      【讨论】:

        猜你喜欢
        • 2013-11-22
        • 2018-08-22
        • 1970-01-01
        • 2016-02-10
        • 2012-12-18
        • 2020-01-17
        • 1970-01-01
        • 2012-02-10
        • 1970-01-01
        相关资源
        最近更新 更多