简体   繁体   English

反应:以“ this”的形式访问目标元素

[英]React: Accessing a target element as 'this'

This has probably been answered before, but I can't seem to google it as it overlaps a bit with .bind(this) questions. 这可能以前已经回答过,但是我似乎无法用Google搜索它,因为它与.bind(this)问题有点重叠。

What I want to do is to refer the calling element as this when I run a function eg 我想做的是在运行函数时将调用元素引用this

highlight()
{
  this.select();
}

<input value={final_line} onClick={this.highlight} ></input>

However, this is undefined after clicking it. 然而, this被点击之后不确定。 So what would the best way to do this? 那么最好的方法是什么? Right now I'm using event.target as a replacement, which works. 现在,我正在使用event.target作为替代品,它可以正常工作。 I've also seen ref being used, but am not sure if this is applicable as I am returning an array of input . 我也看到使用了ref ,但是由于返回数组input ,因此不确定是否适用。

So my question overall is: Is there an alternative to using event.target ? 所以我的总体问题是:是否可以使用event.target替代?

So what would the best way to do this? 那么最好的方法是什么?

There is no way to do this. 没有办法做到这一点。 Using event.target is actually the right way to achieve it. 使用event.target实际上是实现它的正确方法。

If you have several inputs, you should use the name property to identify the targeted element: 如果有多个输入,则应使用name属性来标识目标元素:

inputs.map(input =>
  <input name={input.name} onClick={this.highlight} />
)
highlight(event) {
  this.setState({ [event.target.name]: 'clicked!' })
}

I agree with GG. 我同意GG。 - you should use event.target , but an alternative is to use refs : -您应该使用event.target ,但是另一种方法是使用refs

import { Component } from 'react';
import React from 'react';

class MyComponent extends Component {
  render() {
    const { final_line } = this.props;

    return <input value={final_line}
      onClick={ this.highlight.bind(this)}
      ref="inputToHighlight"
    />;
  }

  highlight() {
    this.refs.inputToHighlight.select();
  }
}

使用箭头函数内的call()作为onClick,将其设置为event.target,例如:

onClick={ (event)=>{onClick.call(event.target, contact.id) }

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

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