2
メニューアイテムがクリックされたときに、同じイベントハンドラを使用したいと考えています。- Reactでクリックされた要素のIDを検出できますか?
バニラのJavaScriptでは、イベントハンドラ 'this'の値が要素を指しています。this.id
を使用すると、これはReactでどのように行われますか。
clickHandler2 and clickHandler3私は1つのイベントハンドラにしたいと思います。異なるのは、クリックされた要素だけです。
コードは以下の通りです:
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.id'が返すもの、おそらく' console.log(this.id) 'を返そうとしていますか?**例:**' this.toggleMarker($ A.el( '#' this.id)); ;または 'console.log(this);'これはあなたが期待しているものをターゲットにして返すことを保証するためですか? – NewToJS