简体   繁体   English

React.js在onclick上传递html元素

[英]Reactjs pass html element on onclick

I'm new to React and I'm trying to pass the HTML element from an onClick event, but I'm not getting the expected result. 我是React新手,正在尝试通过onClick事件传递HTML元素,但没有得到预期的结果。

Here is the code: 这是代码:

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>
        );
     }
}

The desired output would be to get the button's HTML element in the console. 所需的输出将是在控制台中获取按钮的HTML元素。

You need to capture the target of the e (event) instead of the event itself, like this: 您需要捕获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>
       );
  }

}

Here is a demo link: https://codesandbox.io/s/y8xXqopM7 这是一个演示链接: https : //codesandbox.io/s/y8xXqopM7

Hope it helps! 希望能帮助到你!

The method isScrolledIntoView() is bound to the class, not the component instance, so when you refer to this.isScrolledIntoView() in your render method it will return undefined. 方法isScrolledIntoView()绑定到类,而不是组件实例,因此在渲染方法中引用this.isScrolledIntoView()时,它将返回未定义。 Regular React lifecycle methods are bound to the component instance, but for your own custom methods you need to do a little work, you can put it in the constructor: 常规的React生命周期方法绑定到组件实例,但是对于您自己的自定义方法,您需要做一些工作,可以将其放入构造函数中:

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

Or you can use class properties to auto-bind the method: 或者,您可以使用类属性来自动绑定方法:

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

2 things you need to change in your code. 您需要在代码中更改2件事。

1- You have to bind your isScrolledIntoView , and it could be inside your constructor, or doin' this => <button onClick={this.isScrolledIntoView.bind(this)}>Click me</button> 1-您必须bind isScrolledIntoView ,它可能在构造函数内部,或者执行此操作=> <button onClick={this.isScrolledIntoView.bind(this)}>Click me</button>

2- You should target your e event instead of only log e you should 2-您应该以e事件为目标,而不是只应登录e
=> console.log('html element is ', e.target) => console.log('html element is ', e.target)

Nice reading for novices in react 新手反应不错

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM