2017-08-10 31 views
1

不知何故event.currentTarget.textContent显示当选择反应事件。currentTarget的textContent显示所有值

handleChange(event) { 
    console.log(event.currentTarget.textContent); 
} 

render() { 

    var items = []; 
    for (var key in this.props.data) { 
     items.push(<option key={key} value={key}>{this.props.data[key].name}</option>); 
    } 

    return (
     <div className=""> 
      <select onChange={this.handleChange}> 
       <option value=''>Default</option> 
       {items} 
      </select> 
     </div> 

    ); 
} 

控制台日志的结果是所有的结果:DefaultCategory1Category2Cateogry3如何抓住所选选项的文本?

例如:值显示值,但示出了currentTarget当前所有这些:http://jsfiddle.net/3q2bswLy/10/

回答

1

一个select元素的值可以访问使用ELEMENT.value

使用ELEMENT.textContent将为您提供该元素的子元素的所有内容(实际上这是一个包含<option>元素中的所有值的字符串)。

下面是一个普通的JavaScript的例子,但它的工作原理为反应event.currentTarget如出一辙:

console.log(document.querySelector('select').value); 
 
console.log(document.querySelector('select').textContent);
<select> 
 
    <option>val1</option> 
 
    <option selected="selected">val2</option> 
 
    <option>val3</option> 
 
</select>

检查以下的jsfiddle:
https://jsfiddle.net/p89a6r3L/

+0

没有运气: (当使用“document.querySelector('select')时,仍然显示所有结果,但显示其他下拉组件。textContent” –

+0

@JohnnyDerp检查我的回答中的链接 – Dekel

+0

这里是例子:http://jsfiddle.net/3q2bswLy/10/ –