前言

在网页中,点击在多个导航栏切换,被点击的那个导航栏与其他样式不同。然而,看似简答的问题,里面的坑还是有的。

下面是关键代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function TopicItem(props) {
<li
key={props.id}
id={props.id}
calssName={props.activeTopicId === props.id ? "active": ""}
onClick={props.togleTopic}
>
<Link to={props.hash}>
{props.title}
</Link>
</li>
}
class component extends React.Component {
state = {
activeTopicId: TOPICS[0].id,
}
togleTopic = (e) => {
this.setState({
activeTopicId: e.currentTarget.id // 这里是关键
});
}
}

可以看到我们的导航栏结构是li标签里面嵌套着a标签,我想通过点击导航栏,获得点击li标签的id来判断,设置样式,但我么有一点要注意:事件对象有两个类似的属性,target和currentTarget。

A reference to the object that dispatched the event. It is different from event.currentTarget when the event handler is called during the bubbling or capturing phase of the event.

从MDN的官网上说明可以看出它们都是指向事件对象的一个引用,一个是在事件捕获的时候调用,一个是在事件冒泡的时候调用。

所以,如果我使用e.target.id来获得activeTopicId是不可能获得的,因为e.target指向的对象时a标签,没有id。