javascript - 如何在单行中将函数包装在函数中以传递参数而不执行它
问题描述
假设我有一个带有 1 个参数的简单函数
def handle_click(text):
print(text)
我有很多按钮,每个按钮都必须传递不同的文本才能handle_click
起作用
如果我将在按钮内传递一个参数,它将自动执行所有功能,例如:
Button(command=handle_click("display this"))
Button(command=handle_click("display that"))
Button(command=handle_click("show this"))
Button(command=handle_click("show that"))
但我希望在单击按钮时触发此功能
在 React.js 中,我可以使用箭头函数并这样做:
<Button onClick={() => {handleClick("show this")} }>
<Button onClick={() => {handleClick("show that")} }>
<Button onClick={() => {handleClick("so on")} }>
<Button onClick={() => {handleClick("so forth")} }>
解决方案
你可以这样做:
Button(command=lambda: handle_click("display this"))
Button(command=lambda: handle_click("display that"))
Button(command=lambda: handle_click("show this"))
Button(command=lambda: handle_click("show that"))
当您定义这些按钮时,它不会自动运行该函数,并且每当单击这些按钮时,该handle_click
函数将使用您提供的参数运行。
推荐阅读
- python - 如何以低延迟和时间来绘制非常大的音频文件以保存文件?
- json - 使用 Jmeter 的 POST 调用中的多个 Json 有效负载
- javascript - 我希望有人帮助我理解几行代码。有人可以帮我解释一下吗?谢谢
- xcode - 使用 C++17 std::filesystem 是否需要 MacOS 10.15?(Xcode 11.1)
- sas - SAS:用缺失值计算平均值
- swift - 使用滑块在 2 个图像之间转换
- coq - “==>”在coq中是什么意思?
- amazon-web-services - 对 S3* 和 *S3-Glacier 服务使用 *storage-class 'Glacier' 感到困惑
- python - 如何在 Google Colab 上的 Jupyter 笔记本中导入自定义 Python 包和模块?
- r - 创建多列分面函数