React js onClick can't pass value to method

后端 未结 30 1695
北荒
北荒 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:
      <ul onClick={this.onItemClick}>
          {this.props.items.map(item =>
                 <li key={item.id} data-itemid={item.id}>
                     ...
                 </li>
            )}
      </ul>
      

      // 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 (
                  <div>
                    {this.props.items.map(item =>
                        <ListItem key={item.id} item={item} onItemClick={this.handleItemClick}/>
                    )}
                  </div>
              );
          }
      
      }
      
      
      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 (
                  <li key={this.props.item.id} onClick={this.handleItemClick}>{this.props.item.text}</li>
              );
          }
      }
      
    0 讨论(0)
  • 2020-11-22 07:22
    class TableHeader extends Component {
      handleClick = (parameter,event) => {
    console.log(parameter)
    console.log(event)
    
      }
    
      render() {
        return (
          <button type="button" 
    onClick={this.handleClick.bind(this,"dataOne")}>Send</button>
        );
      }
    }
    
    0 讨论(0)
  • 2020-11-22 07:24

    Nowadays, with ES6, I feel we could use an updated answer.

    return (
      <th value={column} onClick={()=>this.handleSort(column)} >{column}</th>
    );
    

    Basically, (for any that don't know) since onClick is expecting a function passed to it, bind works because it creates a copy of a function. Instead we can pass an arrow function expression that simply invokes the function we want, and preserves this. You should never need to bind the render method in React, but if for some reason you're losing this in one of your component methods:

    constructor(props) {
      super(props);
      this.myMethod = this.myMethod.bind(this);
    }
    
    0 讨论(0)
  • 2020-11-22 07:24

    Making alternate attempt to answer OP's question including e.preventDefault() calls:

    Rendered link (ES6)

    <a href="#link" onClick={(e) => this.handleSort(e, 'myParam')}>
    

    Component Function

    handleSort = (e, param) => {
      e.preventDefault();
      console.log('Sorting by: ' + param)
    }
    
    0 讨论(0)
  • 2020-11-22 07:24

    I have added code for onclick event value pass to the method in two ways . 1 . using bind method 2. using arrow(=>) method . see the methods handlesort1 and handlesort

    var HeaderRows  = React.createClass({
        getInitialState : function() {
          return ({
            defaultColumns : ["col1","col2","col2","col3","col4","col5" ],
            externalColumns : ["ecol1","ecol2","ecol2","ecol3","ecol4","ecol5" ],
    
          })
        },
        handleSort:  function(column,that) {
           console.log(column);
           alert(""+JSON.stringify(column));
        },
        handleSort1:  function(column) {
           console.log(column);
           alert(""+JSON.stringify(column));
        },
        render: function () {
            var that = this;
            return(
            <div>
                <div>Using bind method</div>
                {this.state.defaultColumns.map(function (column) {
                    return (
                        <div value={column} style={{height : '40' }}onClick={that.handleSort.bind(that,column)} >{column}</div>
                    );
                })}
                <div>Using Arrow method</div>
    
                {this.state.defaultColumns.map(function (column) {
                    return (
                        <div value={column} style={{height : 40}} onClick={() => that.handleSort1(column)} >{column}</div>
    
                    );
                })}
                {this.state.externalColumns.map(function (column) {
                    // Multi dimension array - 0 is column name
                    var externalColumnName = column;
                    return (<div><span>{externalColumnName}</span></div>
                    );
                })}
    
            </div>);
        }
    });
    
    0 讨论(0)
  • 2020-11-22 07:24

    Simple changed is required:

    Use <th value={column} onClick={that.handleSort} >{column}</th>

    instead of <th value={column} onClick={that.handleSort} >{column}</th>

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