2
我想单击菜单项时使用相同的事件处理程序。- 是否可以检测用React点击的元素的ID?
在香草JavaScript中,事件处理程序的'this'值将指向元素,您可以简单地使用this.id
,这是如何在React中完成的。
clickHandler2 and clickHandler3我想做成一个事件处理程序。唯一不同的是点击元素。
的代码如下:
import React from 'react';
import $ from 'jquery';
class MobileMenu extends React.Component {
constructor (props) {
super(props);
this.clickHandler1 = this.clickHandler1.bind(this);
this.clickHandler2 = this.clickHandler2.bind(this);
this.clickHandler3 = this.clickHandler3.bind(this);
this.state = {
current_item: 'nav_fave'
previous_item: null
};
}
clickHandler1() {
this.toggleMenu();
}
clickHandler2() {
// MenuPage.flip('fave');
this.toggleMenu();
this.toggleMarker($A.el('#nav_fave'));
}
clickHandler3() {
// MenuPage.flip('splash');
this.toggleMenu();
this.toggleMarker($A.el('#nav_splash'));
}
toggleMarker (current_item) {
this.setState({
current_item: current_item
});
if ((this.previous_item !== undefined) && (this.previous_item !== current_item)) {
this.previous_item.style.borderBottom = '';
}
if (this.previous_item !== current_item) {
current_item.style.borderBottom = '3px solid #31baed';
}
this.previous_item = current_item;
}
toggleMenu() {
if (window.getComputedStyle($A.el('#top_menu_list'), null).display === 'block') {
$('#icon_bars').toggleClass('active');
$('#top_menu').slideToggle();
}
}
// ... snip
}
export default MobileMenu
由于您使用的是'jQuery'选择你确定你只是没忘了''#在'this.id'面前? **例如:''this.toggleMarker($ A.el('#'this.id));'你也试过看看'this.id'返回什么,可能是'console.log(this.id) ;'或'console.log(this);'以确保它定位/返回你的期望? – NewToJS