鍍金池/ 問答/HTML5  HTML/ React獲取屬性問題,為什么用e.target.index獲取到的是undef

React獲取屬性問題,為什么用e.target.index獲取到的是undefined?

<div className="form-group">
  <label className="col-md-2 control-label">商品名稱</label>
    <div className="col-md-5">
      <input type="text" className="form-control"  placeholder="輸入商品名稱"
             name="productName" value={this.state.name}
             onChange={(e)=>{this.onChange(e)}}/>
   </div>
</div>
onChange(e){
   console.log(e.target.value);
//這里如果用e.target.getAttribute('value')也可以獲取到值  }

e.target:
圖片描述

 <i className="fa fa-close" index={index} onClick={(e) => this.onImageDelete(e)}>
</i>

    //刪除圖片
  onImageDelete(e){
    let delIndex=e.target.getAttribute('index'); 
    //這里如果用e.target.index獲取的值是undefined,問題是:為什么這里不能用e.target.index獲取呢?
    console.log(delIndex);
  }

e.target:
圖片描述

回答
編輯回答
我甘愿

e.target獲取到的是一個(gè)DOM元素。
DOM相關(guān)的操作分為兩種:

  1. Property
  2. Attribute

Attribute表示的是<tag attr1 attr2>中的attr1attr2,需要通過getAttribute來獲取。
而Property則是一些DOM特殊的屬性值,可以直接.XXX來獲取。
常用的Property有:

  1. className
  2. htmlFor
  3. style
  4. value

對(duì)應(yīng)的Attribute有:

  1. class
  2. for
  3. style
  4. value

這就解釋了為什么target.value可以獲取到而target.index獲取不到,因?yàn)?code>value是Property(只不過因?yàn)楹?code>Attribute重名,所以容易產(chǎn)生誤解),而index不是,所以只能通過getAttribute來獲取。

2017年8月3日 02:04