简体   繁体   中英

Getting ID from div in React.js

So I'm trying to retrieve data in a div attribute in react. JSFiddle shows the problems I'm having. this.state.value is set to an empty string after the event fires.

I started off using the data-* attribute for the div after reading another stack overflow post , but I cannot use jQuery, so I switched to id. Any ideas?

JSFiddle

class GettingAttributes extends React.Component {
  constructor(props) {
    super(props)
    this.state = {value: 'Hello!'};

    this.bar = this.bar.bind(this);
  }

  bar(e){
    this.setState({value: e.target.id})
  }

  render() {
    return (
      <div id="foo" onClick={this.bar}>
        <p>{this.state.value}</p>
      </div>
    );
  }
}

Use

e.currentTarget.id

instead of

e.target.id

.currentTarget will target the element that actually contains the event listener. In your scenario, .target is the p tag with the text in it, which doesn't have an id to set in your state.

You can do it by id as well as data-* attributes. But the preferred method is by data-* attributes.

Please consider this JSFiddle link of your solution.

You should set ref on the element from which you want to extract the data and then you can use it to set data in state. IN code if you replace onClick={this.bar} with onClick={this.barById} then code will extract data from id while in former case it will extract data from data-* attributes.

the reason why you are unable to select the id property is that the current e.target is the child of the <div> , which is <p> . Here is a proposed solution that works:

class GettingAttributes extends React.Component {
  constructor(props) {
    super(props)
    this.state = {value: 'Hello!'};

    this.bar = this.bar.bind(this);
  }

  bar(e){
    this.setState({value: e.target.id})
  }

  render() {

    return (
      <div id="foo" onClick={this.bar}>
        {this.state.value}
      </div>
    );
  }
}

ReactDOM.render(<GettingAttributes />, document.querySelector("#app"))

You may also solve this by adding the click handler to the <p> element:

  <div >
    <p id="foo" onClick={this.bar}>{this.state.value}</p>
  </div>

Using e.currentTarget.id will quickly solve your problem, just know what the currentTarget stands for instead of Target alone. Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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