javascript - React js onClick can't pass value to method -


i want read onclick event value properties. when click on it, see on console:

syntheticmouseevent {dispatchconfig: object, dispatchmarker: ".1.1.0.2.0.0:1", nativeevent: mouseevent, type: "click", target 

my code working correctly. when run can see {column} cant in onclick event.

my code:

var headerrows = react.createclass({     handlesort:  function(value) {        console.log(value);     },     render: function () {         var = this;         return(         <tr>             {this.props.defaultcolumns.map(function (column) {                 return (                     <th value={column} onclick={that.handlesort} >{column}</th>                 );             })}             {this.props.externalcolumns.map(function (column) {                 // multi dimension array - 0 column name                 var externalcolumnname = column[0];                 return ( <th>{externalcolumnname}</th>                 );             })}          </tr>);     } }); 

how can pass value onclick event in react js?

easy way

use arrow function:

return (   <th value={column} onclick={() => this.handlesort(column)}>{column}</th> ); 

this create new function calls handlesort right params.

better way

extract sub-component. problem using arrow function in render call create new function every time, ends causing unneeded re-renders.

if create sub-component, can pass handler , use props arguments, re-render when props change (because handler reference never changes):

sub-component

class tableheader extends component {   handleclick = () => {     this.props.onheaderclick(this.props.value);   }    render() {     return (       <th onclick={this.handleclick}>         {this.props.column}       </th>     );   } } 

main component

{this.props.defaultcolumns.map((column) => (   <tableheader     value={column}     onheaderclick={this.handlesort}   /> ))} 

old easy way (es5)

use .bind pass parameter want:

return (   <th value={column} onclick={that.handlesort.bind(that, column)}>{column}</th> ); 

Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -