onClick on li元素没有正确传递目标ID?

时间:2017-12-05 05:49:00

标签: javascript reactjs material-ui

我正在使用MaterialUI处理ReactJS项目。我有以下代码

{ this.state.categories.map((category, key) => (
      <List>
        <ListItem button id={key} onClick={this.handleClick}>
              <ListItemText primary={category.name} />
              {(category.id === Number(this.state.nestedOpenNum)) ? 
<ExpandLess /> : <ExpandMore />}
        </ListItem>
      </List>
            )

      )}

状态看起来像

this.state = {
  open: false,
  nestedOpen: false,
  nestedOpenNum: 0,
  result: [],
  categories: [{
      id: 0,
      name: "COMPUER SCIENCE",
    }, {
      id: 1,
      name: "BUSINESS",
    }, {
      id: 2,
      name: "ART & HUMANITIES",
    }, {
      id: 3,
      name: "MATH & LOGIC",
    },{
      id: 4,
      name: "SCIENCE",
    }]
};

这是handleClick函数 -

handleClick = (e) => {
this.setState({ nestedOpenNum: e.target.id });
this.setState({ nestedOpen: !this.state.nestedOpen });
console.log(e.target.id );

};

问题

当我点击li元素(绿色区域)的填充区域时,一切都很完美。但是当我点击li元素(蓝色区域)时,e.target.id没有通过。

enter image description here

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

尝试将onClick处理程序作为propI传递给ListItemText组件,它看起来像这个组件阻止其他元素检测其onClick处理程序。

答案 1 :(得分:0)

我认为你应该使用currentTarget而不是target。看看这个https://github.com/DefinitelyTyped/DefinitelyTyped/issues/11508#issuecomment-256045682