简体   繁体   中英

React onClick not working properly

I am trying to use the onClick method in React to log a simple word out when a button is clicked

<button> onClick={console.log('hello world!')}> Submit < / button >           

'hello world!' is only logged out when the page initially loads when i click the button it doesn't log out.

React expects onclick handler to be a function but console.log('hello world!') will only show the message and return undefined . Please try this:

<button onClick={() => console.log('hello world!')}>Submit</button>

Demo: https://jsfiddle.net/iRbouh/6k9w5eem/

onClick accepts a function. You are assigning the return of console.log() execution. What you need to do is something like

<button onClick={() => console.log('hello world!')}>Submit</button>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM