React js onClick can't pass value to method

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

    Easy Way

    Use an arrow function:

    return (
       this.handleSort(column)}>{column}
    );
    

    This will create a new function that calls handleSort with the right params.

    Better Way

    Extract it into a sub-component. The problem with using an arrow function in the render call is it will create a new function every time, which ends up causing unneeded re-renders.

    If you create a sub-component, you can pass handler and use props as the arguments, which will then re-render only when the props change (because the handler reference now never changes):

    Sub-component

    class TableHeader extends Component {
      handleClick = () => {
        this.props.onHeaderClick(this.props.value);
      }
    
      render() {
        return (
          
            {this.props.column}
          
        );
      }
    }
    

    Main component

    {this.props.defaultColumns.map((column) => (
      
    ))}
    

    Old Easy Way (ES5)

    Use .bind to pass the parameter you want, this way you are binding the function with the Component context :

    return (
      {column}
    );
    

提交回复
热议问题