This is a React-Bootstrap-Button:
<Button onClick={console.log('Hello')} className="pull-right">Try me</Button>
I want the function to execute everytime a click the button. However, it will execute on pageload. I read somewhere that I should bind the function:
<Button onClick={console.log('Hello').bind(null)} className="pull-right">Try me</Button>
This gives me the error: Uncaught (in promise) TypeError: Cannot read property 'bind' of undefined.
What should I do?
You are calling log
immediately and then trying to bind
its return value (which is undefined
).
You need to bind the function itself.
You also need to bind it to the console
context and not the null
context. log
cares about the object it is attached to.
onClick={console.log.bind(console, 'Hello')}
Idiomatic React would create the function separately instead of trying to do it inline though:
function myFunction () {
function handleClick(e) {
e.preventDefault();
console.log('Hello');
}
return (
<Button onClick={handleClick} className="pull-right">Try me</Button>
);
}
I think this is what you want:
<button onclick="javascript:console.log('Hello');" className="pull-right">Try me</button>
Notice onclick="javascript:console.log('Hello');"
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.