React报错之Expected `onClick` listener to be a function - chuckQu
source link: https://www.cnblogs.com/chuckQu/p/16596963.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
React报错之Expected `onClick` listener to be a function
正文从这开始~
当我们为元素的onClick
属性传递一个值,但是该值却不是函数时,会产生"Expected onClick
listener to be a function"报错。为了解决该报错,请确保只为元素的onClick
属性传递函数。
这里有个例子来展示错误是如何发生的。
// 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;
当按钮的onClick
属性的期望值是函数时,我们为其传递了一个字符串,从而导致了错误的产生。
为了解决该报错,请确保只为元素的onClick
属性传递函数。
// App.js
const App = () => {
const handleClick = () => {
console.log('button clicked');
};
return (
<div>
<button onClick={handleClick}>Click</button>
</div>
);
};
export default App;
我们向元素的onClick
属性传递了一个函数,顺利的解决了这个错误。然而,注意到我们在向onClick
属性传递函数时并没有调用该函数。
我们传递了函数的引用,而不是函数调用的结果。
如果传递了函数调用的结果,那么事件处理器将在页面加载时立即被调用,这不是我们想要的。
你通常需要做的事情是向事件处理器传递一个参数。你可以通过使用一个内联箭头函数来做到这一点。
// 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
函数是用event
对象和一个数字参数调用的。需要注意的是,我们没有向onClick
属性传递调用handleClick
函数的结果。
我们实际上是将一个函数传递给它,该函数以event
对象为参数,并返回以event
和数字100
为参数的handleClick
函数的调用结果。
不要把调用handleClick
函数的结果传递给onClick
属性,这是非常重要的。因为如若这样的话,当页面加载时,该函数会被立即调用,这可能会导致无限的重新渲染循环。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK