头图

The text starts here~

Overview

When we pass a value for the onClick attribute of the element, but the value is not a function, an "Expected onClick listener to be a function" error will be generated. To resolve this error, make sure to pass functions only for the onClick attribute of the element.

expected-onclick-listener-to-be-function.png

Here is an example to show how the error occurs.

 // App.js
const App = () => {
  // ⛔️ Warning: Expected `onClick` listener to be a function
  // instead got a value of `string` type.
  return (
    <div>
      <button onClick="console.log('Click')">Click</button>
    </div>
  );
};

export default App;

When the expected value of the button's onClick property was a function, we passed it a string, which caused the error.

Transfer Function

To resolve this error, make sure to pass functions only for the onClick attribute of the element.

 // App.js
const App = () => {
  const handleClick = () => {
    console.log('button clicked');
  };

  return (
    <div>
      <button onClick={handleClick}>Click</button>
    </div>
  );
};

export default App;

We passed a function to the element's onClick attribute, which solved the error. However, notice that we are not calling the function when passing the function to the onClick property.

We passed a reference to the function, not the result of the function call.

If the result of the function call is passed, then the event handler will be called as soon as the page loads, which is not what we want.

pass parameters

What you usually need to do is pass an argument to the event handler. You can do this by using an inline arrow function.

 // App.js
import {useState} from 'react';

const App = () => {
  const [count, setCount] = useState(0);

  const handleClick = (event, num) => {
    console.log(event.target);
    console.log('button clicked');
    setCount(count + num);
  };

  return (
    <div>
      <h2>{count}</h2>
      <button onClick={event => handleClick(event, 100)}>Click</button>
    </div>
  );
};

export default App;

handleClick function is called with a event object and a numeric argument. Note that we do not pass the result of calling the handleClick function to the onClick property.

We're actually passing it a function that takes a event object and returns a --- that takes event and a number 100 handleClick The result of the function call.

onclick-listener-function.gif

It is very important not to pass the result of calling the handleClick function to the onClick attribute. Because if so, when the page loads, the function is called immediately, which can lead to an infinite re-render loop.


chuck
303 声望41 粉丝