pass id through on click react.js

前端 未结 6 1571
暖寄归人
暖寄归人 2020-12-08 16:52

Below is my partial code but my question is very simple, how can I get says data-id=\"1\" to my function when user clicked on the li?

render(){
         


        
6条回答
  •  忘掉有多难
    2020-12-08 17:21

    In my opinion, you shouldn't declare functions, nor bind methods within render method. Neither of these:

    onClick={(e) => this.handleClick(e, item.id)}

    onClick={this.handleClick.bind(this, item.id)}

    I know it's plenty of tutoriales showing that syntax. But there's also a considerable number of blog posts warning about why that's not a good idea. Basically, you are creating a new function on each render.

    Go check the manual: https://reactjs.org/docs/handling-events.html

    And I'm aware that in the last two examples it does create functions on render. But react manual also shows this example and says:

    class LoggingButton extends React.Component {
      handleClick() {
        console.log('this is:', this);
      }
    
      render() {
        // This syntax ensures `this` is bound within handleClick
        return (
          
        );
      }
    }
    

    The problem with this syntax is that a different callback is created each time the LoggingButton renders. In most cases, this is fine. However, if this callback is passed as a prop to lower components, those components might do an extra re-rendering. We generally recommend binding in the constructor or using the class fields syntax, to avoid this sort of performance problem.


    BETTER SOLUTION

    So, if you only need to pass one value, then check out the other examples in the manual. Basically you can bind the method in the constructor (or use an experimental syntax to avoid that step).

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

    And how would you get the id/value that you are trying to get? See this example:

    class App extends React.Component {
      constructor(props) {
        super(props);
        this.handleClick = this.handleClick.bind(this);
      }
    
      handleClick({currentTarget}) {    
        console.log(currentTarget.value) // e.currentTarget.value would be equivalent
      }
    
      render() {
        return (
          
        );
      }
    }
    
    ReactDOM.render(
      ,
      document.getElementById('root')
    );
    body {
      padding: 5px;
      background-color: white;
    }
    
    
    
    

    So, if you are using buttons or any form element (accepting a value), you may definitively consider this syntax.

提交回复
热议问题