这是我的react课程中的一个问题的答案。
import React from 'react';
const useState = React.useState;
export default function App() {
const [count, setCount] = useState(0);
const onButtonClick = () => {
setCount(count+1);
};
return (
<div>
<button onClick={onButtonClick}>Click Me!</button>
<h1>Current Count: {count}</h1>
</div>
);
}在react中,为什么在onButtonClick函数中放入参数时会导致错误?
const onButtonClick = (count) => {
setCount(count+1);
};难道我们不需要把count作为参数来使用到函数中吗?我到底搞错了什么?
发布于 2021-03-26 20:38:29
该错误是由于回调将尝试将数字与对象相加而导致的。事件回调中的第一个参数是SyntheticEvent对象。如果你想让你的回调函数接受一个参数,你应该像这样重写你的JSX:
<button onClick={(event) => onButtonClick(event, count)}>Click Me!</button>在你的事件回调中,你可以像这样使用这个参数:
const onButtonClick = (event, count) => {
setCount(count+1);
};由于该函数位于函数组件的local scope中,因此不需要执行上述操作。这意味着它可以访问count变量,这与许多其他编程语言不同。
https://stackoverflow.com/questions/66816996
复制相似问题