div's id attribute is undefined/not getting captured onClick in a react app

前端 未结 5 1434
暗喜
暗喜 2020-12-11 10:05

I\'m mapping data from the api response and rendering multiple divs out of it. Along with that I\'m assigning a unique id from the response to the id attribute of each div l

相关标签:
5条回答
  • 2020-12-11 10:19

    try to set event as function param

    handleClick = (e) => {
      console.log(e.target.id)
      // other stuff
    }
    
    0 讨论(0)
  • 2020-12-11 10:25

    Ok, the problem isn't Reactjs, the problem is the event target.

    You are using e.target when you have to use event.currentTarget, here is the difference.

    • target is the element that triggered the event (e.g., the user clicked on)
    • currentTarget is the element that the event listener is attached to.

    Let see this in an example:

    let tacos = [{
     	person: "John",
      ingredient: 'Guacamole'
     }, {
     	person: 'Sally',
      ingredient: 'Beef'
     }];
    
    class App extends React.Component {
    
      render() {
        return (
          <div>
            <h3>List of tacos:</h3>
            <TacosList tacos={tacos} />
          </div>
        );
      }
    }
    
    class TacosList extends React.Component {
    	constructor(props) {
      	super(props);
    
        this.handleClick = this.handleClick.bind(this);
      }
    	
      handleClick(event) {
      	const currentTarget = event.currentTarget;
        
        console.log(event.target);
        console.log(currentTarget.id);
      }
      
      render() {
        return (
          <div>
            {this.props.tacos.map((taco, index) => (
    					<div className="one" id={`reference-${index}`} key={index} onClick={this.handleClick}>
              	<p>{taco.person}: {taco.ingredient}</p>					  
    					</div>
            ))}
          </div>
        );
      }
    }
    
    ReactDOM.render(<App />, document.getElementById("root"));
    .one {
      padding: 20px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    <div id="root">
    </div>

    Note that you can click on the div and p element and both will trigger the event, in the case of p it will propagate the event up to the div , therefore, it's when the event target changes

    0 讨论(0)
  • 2020-12-11 10:33

    In the constructor, just put this line:

    constructor() {
         this.handleClick = this.handleClick.bind(this);
    }
    

    After this, you will be able to access the ref to the element,

    For more detail please go through this link : https://reactjs.org/docs/handling-events.html

    0 讨论(0)
  • 2020-12-11 10:36

    if you are already using ES6

    I would change the code a bit, so it will easier to understand and work with no special glitches with events target and attributes

    lists.map(list => {
        return (
           <div 
               className='one' 
               key={list.id} 
               onClick={this.handleClick.bind(this, list.id)
    
               <div className='two'>
                 <p>Hello World</p>
                 <span>Foo Bar</span>
               </div>
           </div>
        )
     })
    
     handleClick = (listId) => {
       console.log(listId)
       // other stuff
     }
    

    as you can see here, I just call the method with the list id and I'm done

    0 讨论(0)
  • 2020-12-11 10:44

    The thing is when you define onClick on the topMost parent, you need to use e.currentTarget.id instead of e.target.id since e.target will give you the element on which you clicked rather then the parent on which onClick listener is defined

    class App extends React.Component {
    state = {
      lists: [{id: 1}, {id: 2}, {id:3}]
    }
    render() {
      return (
        <div>
          {this.state.lists.map(list => {
              console.log(list.id)
              return (
              <div className='one' key={list.id} id={list.id} onClick={this.handleClick}>
                <div className='two'>
                  <p>Hello World</p>
                  <span>Foo Bar</span>
                </div>
              </div>
            )
           })
           }
        </div>
      )
    }
    
    handleClick = (e) => {
      console.log(e.currentTarget.id)
      
      // other stuff
    }
    
    }
    
    ReactDOM.render(<App/>, document.getElementById('app'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
    <div id="app"></div>

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