React - Get text of div on click without refs

前端 未结 4 1821
别跟我提以往
别跟我提以往 2020-12-30 06:05

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

var Test = React.createClass({

  handle         


        
相关标签:
4条回答
  • 2020-12-30 06:20

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

    Example:

    handleClick: function(e) {
      alert(e.currentTarget.innerHTML);
    }
    
    0 讨论(0)
  • 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>
      }
    });
    
    0 讨论(0)
  • 2020-12-30 06:29

    Try this way.

    handleMenuItemClick = (event) => {
      console.log(event.target.textContent);
    };
    
    <option onClick={event => this.handleMenuItemClick(event)}>
      item
    </option>
    
    0 讨论(0)
  • 2020-12-30 06:30

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

    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 React and not ReactDOM.

    0 讨论(0)
提交回复
热议问题