通过教程学习 React,我不明白为什么我必须创建一个新函数来传递给 JSX onClick
不能只使用从 React 返回的 useState
打电话。
下面的工作是调用 handleButtonClick
在按钮上单击,但如果我只是通过 setMessage
它不起作用改为使用字符串调用函数。
作品:
function App() {
const [message, setMessage] = React.useState('Javascript is so cool');
function handleButtonClick() {
setMessage('This is a new message');
}
return (
<div>
<h1>{message}</h1>
<button onClick={handleButtonClick}>Update The Message!</button>
</div>
);
}
不起作用:
function App() {
//Javascript goes here
const [message, setMessage] = React.useState('Javascript is so cool');
function handleButtonClick() {
setMessage('This is a new message');
}
return (
<div>
<h1>{message}</h1>
<button onClick={setMessage('Boom')}>Update The Message!</button>
</div>
);
我看到了:
<button onClick={() => setMessage('Boom')}>Update The Message!</button>
有效,但我不明白为什么必须这样设置而且我不能只使用 setMessage
以与我使用 handleButtonClick
相同的方式调用打电话。
最佳答案
发生这种情况是因为当您将函数放在括号中时,您会调用该函数,如果您只将函数放在不带括号的位置,则会传递“指针”。
一个例子:
// log function
function logTheType(param) {
console.log(typeof param);
}
// sum function
function sum(a, b) {
return a + b;
}
// sum is a function
logTheType(sum);
// res: function
// you are calling sum and send the return to the logTheType
logTheType(sum(1, 5));
// res: number
// you pass an anonymous function
logTheType(() => sum(1, 5));
// res: function
关于javascript - onClick 中的 React 状态设置函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59567856/