React js onClick can't pass value to method
1. Using Arrow Function:
button onClick={() = myMethod('value')} Click Me /button
In this example, myMethod will receive 'value' as its argument when the button is clicked.
2. Binding in the Constructor (Class Component Only):
class MyComponent extends React.Component {
handleClick(value) {
// Access the value here
console.log(value);
}
render() {
return (
button onClick={() = this.handleClick('value')} Click Me /button
);
}
}
This method ensures that the correct context (this) is maintained and the value is passed to the method.
コメント