React js onClick can't pass value to method

后端 未结 30 2131
北荒
北荒 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: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 => (
          
      {props.items.map(item =>
    • console.log(item.id)}> ...
    • )}
    );

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

    const List = props => (
          
      {props.items.map(item => )}
    ); const ListItem = props => { const _onClick = () => { console.log(props.item.id); } return (
  • ...
  • ); });

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

提交回复
热议问题