2017-06-15 61 views
0

我是React的新手,我試圖從onClick事件傳遞HTML元素,但沒有得到預期的結果。Reactjs在onclick上傳遞html元素

下面是代碼:

import React, { Component } from 'react'; 

export class Header extends Component{ 
    isScrolledIntoView (e){ 
    console.log('html element is ',e) 
    } 

    render(){ 
     return(
      <div> 
       <button onClick={this.isScrolledIntoView.()}>Click me</button> 
      </div> 
     ); 
    } 
} 

所需的輸出將得到該按鈕的HTML元素在控制檯中。

回答

2

您需要捕獲e(事件)的目標,而不是事件本身,就像這樣:

import React, { Component } from 'react'; 

export class Header extends Component { 

    isScrolledIntoView (e) { 
    console.log('html element is ', e.target) 
    } 

    render() { 
     return (
      <div> 
       <button onClick={this.isScrolledIntoView.bind(this)}>Click me</button> 
      </div> 
     ); 
    } 

} 

這裏是一個演示鏈接:https://codesandbox.io/s/y8xXqopM7

希望它能幫助!

+0

哇新手console.log('html element is ', e.target)

尼斯的閱讀,它的工作!只是好奇這裏的'e'和e.target是什麼意思? – jackysatpal

+0

我做了一個演示鏈接,以防萬一:https://codesandbox.io/s/y8xXqopM7 –

+0

它返回觸發事件的元素。 – thodorisbais

0

方法isScrolledIntoView()綁定到類,而不是組件實例,所以當您在渲染方法中引用this.isScrolledIntoView()時,它將返回undefined。定期陣營生命週期方法被綁定到組件實例,但對於自己的自定義方法,你需要做一些工作,你可以把它在構造函數中:

constructor(props) { 
    this.isScrolledIntoView = this.isScrolledIntoView.bind(this); 
} 

或者你可以使用類屬性自動 - 綁定方法:

isScrolledIntoView = (e) => { 
    // do stuff 
} 
0

2您需要在代碼中更改的東西。

1 - 你必須bindisScrolledIntoView,它可能是你的構造函數中,或上來的這=><button onClick={this.isScrolledIntoView.bind(this)}>Click me</button>

2 - 您應該儘量E事件,而不是隻記錄Ë你應該
= >在react