Col*_*bus 3 javascript reactjs
通过教程学习 React,我不明白为什么我必须创建一个新函数来传递给 JSX onClick,而不能只使用从 ReactuseState调用返回的函数。
下面的代码在单击按钮时调用时有效,但如果我只是用字符串传递函数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>
);
}
Run Code Online (Sandbox Code Playgroud)
不起作用:
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>
);
Run Code Online (Sandbox Code Playgroud)
我看到:
<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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
916 次 |
| 最近记录: |