React事件currentTarget textContent显示所有值

时间:2017-08-10 21:21:19

标签: reactjs

以某种方式event.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如何获取所选的选项文本?

示例:value显示值,但currentTarget显示所有值:http://jsfiddle.net/3q2bswLy/10/

1 个答案:

答案 0 :(得分: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/