2017-06-15 62 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