在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問(wèn)答/HTML/ react點(diǎn)擊刪除當(dāng)前項(xiàng),獲取不到data-index屬性?

react點(diǎn)擊刪除當(dāng)前項(xiàng),獲取不到data-index屬性?

clipboard.png

要實(shí)現(xiàn)功能,點(diǎn)擊刪除按鈕會(huì)刪除當(dāng)前子組件,子組件放在數(shù)組中;計(jì)劃是通過(guò)點(diǎn)擊子組件刪除對(duì)應(yīng)數(shù)組中子組件的那一項(xiàng),每個(gè)子組件的index={index},點(diǎn)擊后通過(guò)e.target.getAttribute("data-index")為啥獲取不到index呢,結(jié)果是null。

import React, { Component } from 'react';
import './App.css';
import Add from './components/Add'
import Item from './components/Item'

class App extends Component {
  constructor() {
    super();
    this.state = {
        name: "",
        age: null,
        gender: "",
        infoList: []
    };
  }

  /*shouldComponentUpdate() {
    //alert("shouldComponentUpdate");
    return true;        // 記得要返回true
  }*/

  renderItem() {
    return <Item />;
  }

  changeList = (e) => {
    //let infoList = this.state.infoList;
    this.setState({
      //name:childState.name,
      //age:childState.age,
      //gender:childState.gender
    });
      //此處獲取index
    console.log(e.target.parentNode.getAttribute("data-index"))
    //infoList.pop()
  }

  getChildInfo = (childState) => {
    let infoList = this.state.infoList;
    
    this.setState({
      //name:childState.name,
      //age:childState.age,
      //gender:childState.gender
    });
    infoList.push(childState)
  }

  render() {
    let infoList = this.state.infoList;
    return (
      <div className="App">
        <header className="App-header">
          <h1 className="App-title">A list for users</h1>
        </header>
        <p className="App-intro">
          請(qǐng)輸入用戶信息<code>src/App.js</code> 點(diǎn)擊修改
        </p>
        此處為App父組件
        <p className="Add-show">
          姓名:{this.state.name} 
          年齡:{this.state.age} 
          性別:{this.state.gender}
        </p>
       
        <ul className="User-ifo">
          此處為tem子組件
        </ul>
        {
          infoList.map((item,index)=>{
            return (
              <div key={index} index={index} >
                <Item key={item?item:index} index={index} name={item.name} age={item.age} gender={item.gender} />
                <button onClick={this.changeList}>刪除</button>
              </div>
            )
          })
        }
        <Add toParent={this.getChildInfo.bind(this)}/>
        
      </div>

    );
  }
}

export default App;

回答
編輯回答
真難過(guò)

<button/> 上沒(méi)有data-index屬性 加上就行了

2017年8月14日 06:07
編輯回答
薔薇花

e.target.parentNode.getAttribute("data-index")??你div沒(méi)data-index這個(gè)屬性吧,只有index

e.target.parentNode.getAttribute("index")

或者直接寫(xiě)

<button onClick={()=>this.changeList(e,index)}>刪除</button>

  changeList(e,i){
    
    console.log(i);
   
  }
2017年6月18日 01:38