Javascript React - 在没有参考的情况下点击获取 div 的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36414432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:02:07  来源:igfitidea点击:

React - Get text of div on click without refs

javascripthtmlreactjs

提问by chrisrhyno2003

Is there an example where we can retrieve the value of a React element without the usage of refs? Is that possible?

有没有一个例子,我们可以在不使用 refs 的情况下检索 React 元素的值?那可能吗?

var Test = React.createClass({

  handleClick: function() {
    alert(this.text);
  },
  render: function() {
    <div className="div1" onClick={this.handleClick}> HEkudsbdsu </div>
  }
})

回答by chrisrhyno2003

I found a working answer:

我找到了一个有效的答案:

var Hello = React.createClass({
  handleClick: function(event) {
    alert(event.currentTarget.textContent);
  },
  render: function() {
    return <div className="div1" onClick={this.handleClick}> HEkudsbdsu </div>
  }
});

回答by MattDiamant

I suppose you can just get the DOM Node with ReactDOM.findDOMNode(this);, and then get its innerTextor whatever you need from it.

我想您可以使用 获取 DOM 节点ReactDOM.findDOMNode(this);,然后从中获取它innerText或您需要的任何内容。

var Hello = React.createClass({
  handleClick: function() {
    var domNode = ReactDOM.findDOMNode(this);
    alert(domNode.innerText);
  },
  render: function() {
    return <div className="div1" onClick={this.handleClick}> HEkudsbdsu </div>
  }
});

This is a bit of a runabout way of doing it, but it will work.

这种做法有点笨拙,但它会奏效。

Note that pre 0.14 React, you'll just be using Reactand not ReactDOM.

请注意,在 0.14 React 之前,您将只使用React而不是ReactDOM.

回答by Ikram - Ud - Daula

Try this way.

试试这个方法。

handleMenuItemClick = (event) => {
  console.log(event.target.textContent);
};

<option onClick={event => this.handleMenuItemClick(event)}>
  item
</option>

回答by dimpiax

If you want to retrieve text, use innerTextproperty, if html – innerHTML.

如果要检索文本,请使用innerText属性,如果 html – innerHTML

Example:

例子:

handleClick: function(e) {
  alert(e.currentTarget.innerHTML);
}