2017-12-27 8 views
0

ラッピング要素をクリックすると、そのラッピング要素でトリガする関数が必要です。代わりに、それは最も内側の要素を引き金にするようです。ReactJSラッピング要素をクリックする方法は?

「yo」ログをクリックすると、undefinedが表示されます。 "yo"と "lip"の間のスペースをクリックしてください。1; 「リップ」ログundefinedをクリックします。

すべて3がログ1を期待します。

import React from 'react'; 

export default class Foo extends React.Component { 
    something = e => { 
    e.stopPropagation() 
    console.log(e.target.dataset.index) 
    } 

    render() { 
    return (
     <section data-index={1} onClick={this.something} ref={e => { this.section = e }}> 
     <h1 style={{ marginBottom: 30 }}>yo</h1> 
     <p>lip</p> 
     </section> 
    ) 
    } 
} 

CodeSandbox Demo

答えて

1

あなたはe.targetの代わりにe.currentTargetを使用することによって、あなたが望む行動を取得します。

docs for e.currentTarget state:イベントはDOMを横断するとき

は、イベントの現在のターゲットを識別します。イベントが発生した要素を識別するevent.targetではなく、常にイベントハンドラがアタッチされている要素を参照します。

ここはa fork of your codesandbox using e.currentTargetです。

import React from 'react'; 

export default class Foo extends React.Component { 
    something = e => { 
    e.stopPropagation() 
    console.log(e.currentTarget.dataset.index) 
    } 

    render() { 
    return (
     <section data-index={1} onClick={this.something} ref={e => { this.section = e }}> 
     <h1 style={{ marginBottom: 30 }}>yo</h1> 
     <p>lip</p> 
     </section> 
    ) 
    } 
} 
+0

素晴らしい、ありがとうございました。 =) – corysimmons

3
import React from 'react'; 

export default class Foo extends React.Component { 
    something = e => { 
    e.stopPropagation() 
    //console.log(e.target.dataset.index) 
    console.log(e.currentTarget.dataset.index) 
    } 

    render() { 
    return (
     <section data-index={1} onClick={this.something} ref={e => { this.section = e }}> 
     <h1 style={{ marginBottom: 30 }}>yo</h1> 
     <p>lip</p> 
     </section> 
    ) 
    } 
} 
関連する問題