React js onClick can't pass value to method

后端 未结 30 1692
北荒
北荒 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:16

    There were a lot of performance considerations, all in the vacuum.
    The issue with this handlers is that you need to curry them in order to incorporate the argument that you can't name in the props.
    This means that the component needs a handler for each and every clickable element. Let's agree that for a few buttons this is not an issue, right?
    The problem arises when you are handling tabular data with dozens of columns and thousands of rows. There you notice the impact of creating that many handlers.

    The fact is, I only need one.
    I set the handler at the table level (or UL or OL...), and when the click happens I can tell which was the clicked cell using data available since ever in the event object:

    nativeEvent.target.tagName
    nativeEvent.target.parentElement.tagName 
    nativeEvent.target.parentElement.rowIndex
    nativeEvent.target.cellIndex
    nativeEvent.target.textContent
    

    I use the tagname fields to check that the click happened in a valid element, for example ignore clicks in THs ot footers.
    The rowIndex and cellIndex give the exact location of the clicked cell.
    Textcontent is the text of the clicked cell.

    This way I don't need to pass the cell's data to the handler, it can self-service it.
    If I needed more data, data that is not to be displayed, I can use the dataset attribute, or hidden elements.
    With some simple DOM navigation it's all at hand.
    This has been used in HTML since ever, since PCs were much easier to bog.

    0 讨论(0)
  • 2020-11-22 07:18

    [[h/t to @E.Sundin for linking this in a comment]

    The top answer (anonymous functions or binding) will work, but it's not the most performant, as it creates a copy of the event handler for every instance generated by the map() function.

    This is an explanation of the optimal way to do it from the ESLint-plugin-react:

    Lists of Items

    A common use case of bind in render is when rendering a list, to have a separate callback per list item:

    const List = props => (
          <ul>
            {props.items.map(item =>
              <li key={item.id} onClick={() => console.log(item.id)}>
                ...
              </li>
            )}
          </ul>
        );
    

    Rather than doing it this way, pull the repeated section into its own component:

    const List = props => (
          <ul>
            {props.items.map(item =>
              <ListItem 
                key={item.id} 
                item={item} 
                onItemClick={props.onItemClick} // assume this is passed down to List
               />
            )}
          </ul>
        );
    
    
    const ListItem = props => {
      const _onClick = () => {
        console.log(props.item.id);
      }
        return (
          <li onClick={_onClick}>
            ...
          </li>
        );
    
    });
    

    This will speed up rendering, as it avoids the need to create new functions (through bind calls) on every render.

    0 讨论(0)
  • 2020-11-22 07:18

    I realize this is pretty late to the party, but I think a much simpler solution could satisfy many use cases:

        handleEdit(event) {
            let value = event.target.value;
        }
    
        ...
    
        <button
            value={post.id}
            onClick={this.handleEdit} >Edit</button>
    

    I presume you could also use a data- attribute.

    Simple, semantic.

    0 讨论(0)
  • 2020-11-22 07:20

    Below is the example which passes value on onClick event.

    I used es6 syntax. remember in class component arrow function does not bind automatically, so explicitly binding in constructor.

    class HeaderRows extends React.Component {
    
        constructor(props) {
            super(props);
            this.handleSort = this.handleSort.bind(this);
        }
    
        handleSort(value) {
            console.log(value);
        }
    
        render() {
            return(
                <tr>
                    {this.props.defaultColumns.map( (column, index) =>
                        <th value={ column } 
                            key={ index } 
                            onClick={ () => this.handleSort(event.target.value) }>
                            { column }
                        </th>
                    )}
    
                    {this.props.externalColumns.map((column, index)  =>
                        <th value ={ column[0] }
                            key={ index }>
                            {column[0]}
                        </th>
                    )}
                </tr>
             );
        }
    }
    
    0 讨论(0)
  • 2020-11-22 07:20

    Coming out of nowhere to this question, but i think .bind will do the trick. Find the sample code below.

    const handleClick = (data) => {
        console.log(data)
    }
    
    <button onClick={handleClick.bind(null, { title: 'mytitle', id: '12345' })}>Login</button>
    
    0 讨论(0)
  • 2020-11-22 07:21

    Implementing show total count from an object by passing count as a parameter from main to sub components as described below.

    Here is MainComponent.js

    import React, { Component } from "react";
    
    import SubComp from "./subcomponent";
    
    class App extends Component {
    
      getTotalCount = (count) => {
        this.setState({
          total: this.state.total + count
        })
      };
    
      state = {
        total: 0
      };
    
      render() {
        const someData = [
          { name: "one", count: 200 },
          { name: "two", count: 100 },
          { name: "three", count: 50 }
        ];
        return (
          <div className="App">
            {someData.map((nameAndCount, i) => {
              return (
                <SubComp
                  getTotal={this.getTotalCount}
                  name={nameAndCount.name}
                  count={nameAndCount.count}
                  key={i}
                />
              );
            })}
            <h1>Total Count: {this.state.total}</h1>
          </div>
        );
      }
    }
    
    export default App;
    

    And Here is SubComp.js

    import React, { Component } from 'react';
    export default class SubComp extends Component {
    
      calculateTotal = () =>{
        this.props.getTotal(this.props.count);
      }
    
      render() {
        return (
          <div>
            <p onClick={this.calculateTotal}> Name: {this.props.name} || Count: {this.props.count}</p>
          </div>
        )
      }
    };
    

    Try to implement above and you will get exact scenario that how pass parameters works in reactjs on any DOM method.

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