Thursday, October 25, 2018

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



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: Object, dispatchMarker: ".1.1.0.2.0.0:1", nativeEvent: MouseEvent, type: "click", target



My code is working correctly. When I run I can see {column} but can't get it in the onClick event.



My Code:



var HeaderRows = React.createClass({
handleSort: function(value) {
console.log(value);
},

render: function () {
var that = this;
return(

{this.props.defaultColumns.map(function (column) {
return (
{column}
);
})}
{this.props.externalColumns.map(function (column) {

// Multi dimension array - 0 is column name
var externalColumnName = column[0];
return ( {externalColumnName});
})}

);
}
});



How can I pass a value to the onClick event in React js?


Answer



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) => (

value={column}
onHeaderClick={this.handleSort}
/>
))}





Old Easy Way (ES5)




Use .bind to pass the parameter you want:



return (
{column}
);

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...