React js onClick can't pass value to method

后端 未结 30 1672
北荒
北荒 2020-11-22 07:05

I want to read the onClick event value properties. But when I click on it, I see something like this on the console:

SyntheticMouseEvent {dispatchConfig: Ob         


        
30条回答
  •  隐瞒了意图╮
    2020-11-22 07:21

    I have below 3 suggestion to this on JSX onClick Events -

    1. Actually, we don't need to use .bind() or Arrow function in our code. You can simple use in your code.

    2. You can also move onClick event from th(or ul) to tr(or li) to improve the performance. Basically you will have n number of "Event Listeners" for your n li element.

      So finally code will look like this:
      
        {this.props.items.map(item =>
      • ...
      • )}

      // And you can access item.id in onItemClick method as shown below:

      onItemClick = (event) => {
         console.log(e.target.getAttribute("item.id"));
      }
      
    3. I agree with the approach mention above for creating separate React Component for ListItem and List. This make code looks good however if you have 1000 of li then 1000 Event Listeners will be created. Please make sure you should not have much event listener.

      import React from "react";
      import ListItem from "./ListItem";
      export default class List extends React.Component {
      
          /**
          * This List react component is generic component which take props as list of items and also provide onlick
          * callback name handleItemClick
          * @param {String} item - item object passed to caller
          */
          handleItemClick = (item) => {
              if (this.props.onItemClick) {
                  this.props.onItemClick(item);
              }
          }
      
          /**
          * render method will take list of items as a props and include ListItem component
          * @returns {string} - return the list of items
          */
          render() {
              return (
                  
      {this.props.items.map(item => )}
      ); } } import React from "react"; export default class ListItem extends React.Component { /** * This List react component is generic component which take props as item and also provide onlick * callback name handleItemClick * @param {String} item - item object passed to caller */ handleItemClick = () => { if (this.props.item && this.props.onItemClick) { this.props.onItemClick(this.props.item); } } /** * render method will take item as a props and print in li * @returns {string} - return the list of items */ render() { return (
    4. {this.props.item.text}
    5. ); } }

提交回复
热议问题